# ------------------------------
# Stage 1 - Build Front Assets
# ------------------------------
FROM node:20-slim AS assets
WORKDIR /app
ENV NODE_OPTIONS="--max-old-space-size=2048" CI=true

# Copier les fichiers nécessaires pour installer les dépendances JS
COPY package.json package-lock.json* yarn.lock* ./
RUN --mount=type=cache,target=/root/.yarn \
    --mount=type=cache,target=/root/.npm \
    bash -lc 'if [ -f yarn.lock ]; then corepack enable && corepack prepare yarn@1.22.22 --activate && yarn install --frozen-lockfile --non-interactive --no-progress; else npm ci --no-audit --no-fund --progress=false; fi'

# Copier les sources front (par exemple /assets et webpack config)
COPY assets ./assets
COPY webpack.config.js .
COPY .babelrc* .eslintrc* postcss.config.js* tsconfig.json* ./

# Lancer le build (adapté à Symfony Encore ou ton build script)
RUN --mount=type=cache,target=/app/node_modules/.cache \
    bash -lc 'if [ -f package.json ]; then if [ -f yarn.lock ]; then yarn build; else npm run build; fi; fi'

# docker/stack/php/Dockerfile
FROM php:8.2-fpm-bookworm

RUN set -eux; \
  apt-get update; \
  apt-get install -y --no-install-recommends \
    ca-certificates tzdata curl wget git unzip pkg-config \
    libzip-dev libicu-dev libpq-dev libjpeg62-turbo-dev libpng-dev libwebp-dev libfreetype6-dev \
    librabbitmq-dev libssl-dev \
    fontconfig fonts-dejavu-core \
    acl cron supervisor vim-tiny; \
  fc-cache -f; \
  rm -rf /var/lib/apt/lists/*

# Déps runtime utiles (déjà installées chez toi, ajuste si besoin)
RUN set -eux; \
  apt-get update; \
  apt-get install -y --no-install-recommends \
    ca-certificates curl fontconfig \
    libjpeg62-turbo libpng16-16 libxrender1 libxext6 libx11-6 \
    xfonts-base; \
  rm -rf /var/lib/apt/lists/*

# ---- wkhtmltopdf via APT (Debian Bookworm) ----
RUN set -eux; \
  apt-get update; \
  apt-get install -y --no-install-recommends \
    wkhtmltopdf fontconfig xfonts-base; \
  rm -rf /var/lib/apt/lists/*

# Vérification claire
RUN /usr/bin/wkhtmltopdf --version

# ---- Extensions PHP (GD, intl, pdo_mysql, zip) ----
# (nécessite que libjpeg/libpng/libwebp/libfreetype/libicu-dev soient installés côté build)
RUN set -eux; \
    docker-php-ext-configure gd --with-freetype --with-jpeg --with-webp; \
    docker-php-ext-install -j"$(nproc)" gd intl pdo_mysql zip

# ---- PECL (amqp, redis) ----
# (amqp nécessite librabbitmq-dev et pkg-config déjà installés plus haut)
RUN set -eux; \
    pecl install amqp redis; \
    docker-php-ext-enable amqp redis

# (Optionnel) Vérifier GD sans quotes complexes
RUN php -r 'var_export(extension_loaded("gd")); echo PHP_EOL;'; \
    php -r '$i=function_exists("gd_info")?gd_info():[]; print_r($i);'


RUN apt-get update && apt-get install -y \
    imagemagick \
    libmagickwand-dev \
    libmagickcore-dev \
    && rm -rf /var/lib/apt/lists/*


RUN pecl install imagick \
    && docker-php-ext-enable imagick

RUN curl -sS https://getcomposer.org/installer \
  | php -- --install-dir=/usr/local/bin --filename=composer

WORKDIR /var/www

COPY composer.json composer.lock* symfony.lock* ./
ENV COMPOSER_ALLOW_SUPERUSER=1 \
    COMPOSER_MEMORY_LIMIT=-1 \
    COMPOSER_HOME=/tmp/composer

RUN --mount=type=cache,target=/tmp/composer/cache \
    composer install --no-dev --prefer-dist --no-interaction --no-scripts

COPY --chown=www-data:www-data . /var/www

# Copy built assets from frontend stage
COPY --from=assets /app/public/build /var/www/public/build

RUN composer dump-autoload --classmap-authoritative --no-dev --no-interaction

# 6) Permissions initiales (seront reforcées à chaque boot par entrypoint)
RUN set -eux; \
  mkdir -p \
    var/cache/prod/doctrine/orm/Proxies \
    var/log \
    public \
    public/build \
    public/uploads; \
  chown -R www-data:www-data /var/www; \
  # Permissions pour le runtime (écriture app) \
  find var -type d -exec chmod 775 {} \; || true; \
  find var -type f -exec chmod 664 {} \; || true; \
  # Permissions lecture publique pour Nginx/clients \
  find public -type d -exec chmod 755 {} \; || true; \
  find public -type f -exec chmod 644 {} \; || true; \
  # Dossiers d'assets générés et d'uploads → écriture par www-data \
  chown -R www-data:www-data public/build public/uploads; \
  chmod -R 775 public/build public/uploads || true

# 7) PHP-FPM tuning minimal (status/ping utiles)
RUN { \
  echo "[www]"; \
  echo "pm.status_path = /status"; \
  echo "ping.path = /ping"; \
  echo "clear_env = no"; \
} | tee /usr/local/etc/php-fpm.d/z-www-extra.conf >/dev/null

# 8) Entrypoint “hardened” (fix droits, pas de warmup auto)
COPY docker/stack/php/entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh

ENV APP_ENV=prod \
    APP_DEBUG=0 \
    RUN_MIGRATIONS=false \
    RUN_WARMUP=false

# 9) Garantie finale : tout /var/www/var doit être www-data dans l'image baked.
#    Sans ça, des résidus root-owned (cache de container Symfony compilé pendant
#    le build) bloquent php-fpm au premier hit avec "Unable to write in cache".
RUN set -eux; \
    rm -rf /var/www/var/cache/prod/* /var/www/var/cache/prod/.[!.]* 2>/dev/null || true; \
    chown -R www-data:www-data /var/www/var; \
    find /var/www/var -type d -exec chmod 775 {} \;; \
    find /var/www/var -type f -exec chmod 664 {} \;

HEALTHCHECK --interval=30s --timeout=5s --retries=3 --start-period=10s \
  CMD php -v >/dev/null || exit 1

ENTRYPOINT ["entrypoint.sh"]

# Crontab attendue par l’entrypoint
COPY ./docker/stack/worker/crontab /etc/cron.d/kplan
RUN chmod 0644 /etc/cron.d/kplan

# Scripts utilisés par la crontab / workers
COPY ./docker/stack/worker/scripts/ /usr/local/bin/
RUN chmod -R 0755 /usr/local/bin

# Supervisord config pour APP_ROLE=worker
COPY ./docker/stack/worker/worker.conf /etc/supervisor/conf.d/worker.conf

CMD ["php-fpm","-F"]
