ARG DOCKER_PHP_VERSION=8.4.6

FROM php:${DOCKER_PHP_VERSION}-fpm-bullseye AS php-base

ARG DOCKER_NODE_VERSION=24.12.0
ENV DOCKER_NODE_VERSION="${DOCKER_NODE_VERSION}"

# Installer les dépendances et extensions PHP nécessaires
RUN apt-get update && apt-get install -y \
        libicu-dev \
        libpq-dev \
        libpng-dev \
        libzip-dev \
        libxml2-dev \
        ca-certificates \
        gnupg \
        libbz2-dev \
        libgmp-dev \
        libldap2-dev \
        libonig-dev \
        libsodium-dev \
        libxslt1-dev \
        zlib1g-dev \
        libssl-dev \
        wget \
        git \
        unzip \
    && docker-php-ext-install -j$(nproc) \
            intl \
            zip \
            bcmath \
            bz2 \
            calendar \
            exif \
            gd \
            gettext \
            gmp \
            ldap \
            pcntl \
            pdo_pgsql \
            soap \
            sockets \
            sysvsem \
            xsl \
    && docker-php-ext-enable opcache \
    && rm -rf /var/lib/apt/lists/* /tmp/*

# Installation de node
RUN wget -qO- "https://nodejs.org/dist/v${DOCKER_NODE_VERSION}/node-v${DOCKER_NODE_VERSION}-linux-x64.tar.xz" | tar xJC /tmp/ && \
    cp -r /tmp/node-v${DOCKER_NODE_VERSION}-linux-x64/bin /usr/ && \
    cp -r /tmp/node-v${DOCKER_NODE_VERSION}-linux-x64/include /usr/ && \
    cp -r /tmp/node-v${DOCKER_NODE_VERSION}-linux-x64/lib /usr/ && \
    cp -r /tmp/node-v${DOCKER_NODE_VERSION}-linux-x64/share /usr/ && \
    rm -rf /tmp/*

# Installation de composer
RUN curl --insecure https://getcomposer.org/composer.phar -o /usr/bin/composer && chmod +x /usr/bin/composer

WORKDIR /var/www/html

# Copier les fichiers projet
COPY . /var/www/html

# Installation des dépendances PHP (prod)
RUN composer install --no-dev --optimize-autoloader --no-interaction

# Génération des clés JWT si absentes
RUN php bin/console lexik:jwt:generate-keypair --skip-if-exists

# Build du frontend
RUN cd frontend && npm ci && npm run build:dist && rm -rf node_modules

# Permissions
RUN chown -R www-data:www-data /var/www/html/var /var/www/html/frontend/dist

# PHP prod config
COPY infra/prod/php-prod.ini /usr/local/etc/php/php.ini

EXPOSE 9000

# ── Nginx stage ──
FROM nginx:1.27-alpine AS nginx

COPY infra/prod/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=php-base /var/www/html/public /var/www/html/public
COPY --from=php-base /var/www/html/frontend/dist /var/www/html/frontend/dist
