FROM php:8.4-fpm-bookworm AS app
WORKDIR /var/www/html

ENV COMPOSER_ALLOW_SUPERUSER=1
ENV COMPOSER_PROCESS_TIMEOUT=600

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
        default-mysql-client \
        default-libmysqlclient-dev \
        git \
        libicu-dev \
        libzip-dev \
        unzip \
    && docker-php-ext-install -j"$(nproc)" bcmath intl pcntl pdo_mysql zip \
    && apt-mark manual libzip4 libicu72 \
    && apt-get purge -y --auto-remove \
        default-libmysqlclient-dev \
        libicu-dev \
        libzip-dev \
    && rm -rf /var/lib/apt/lists/*

COPY docker/php/composer.phar /usr/local/bin/composer
RUN chmod +x /usr/local/bin/composer

COPY docker/php/php.ini /usr/local/etc/php/conf.d/99-production.ini
COPY docker/php/opcache.ini /usr/local/etc/php/conf.d/99-opcache.ini

COPY composer.json composer.lock ./
RUN composer install \
        --no-dev \
        --no-autoloader \
        --no-scripts \
        --prefer-dist \
        --no-interaction \
    && composer check-platform-reqs --no-dev

COPY . .

RUN composer dump-autoload --no-dev --optimize --no-scripts \
    && php artisan package:discover --ansi \
    && APP_KEY=base64:dGVtcG9yYXJ5a2V5Zm9yZG9ja2VyYnVpbGRvbmx5= php artisan l5-swagger:generate --no-interaction \
    && mkdir -p \
        storage/app/public \
        storage/framework/cache/data \
        storage/framework/sessions \
        storage/framework/views \
        storage/logs \
        storage/api-docs \
        bootstrap/cache \
    && rm -rf public/storage \
    && ln -s ../storage/app/public public/storage \
    && chown -R www-data:www-data storage bootstrap/cache

COPY docker/entrypoint.sh /usr/local/bin/docker-entrypoint
RUN chmod +x /usr/local/bin/docker-entrypoint

EXPOSE 9000

ENTRYPOINT ["docker-entrypoint"]
CMD ["php-fpm"]

FROM nginx:1.27-alpine AS nginx

COPY docker/nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=app /var/www/html/public /var/www/html/public

EXPOSE 80

# npm build (run locally before docker build):
# npm ci && npm run build
