FROM docker.arvancloud.ir/php:8.4-fpm-bookworm AS app
WORKDIR /var/www/html

ENV COMPOSER_ALLOW_SUPERUSER=1

COPY docker/php/install-php-extensions /usr/local/bin/install-php-extensions

RUN if [ -f /etc/apt/sources.list.d/debian.sources ]; then \
        sed -i \
            -e 's|https\?://deb\.debian\.org/debian|http://mirror.arvancloud.ir/debian|g' \
            -e 's|https\?://security\.debian\.org/debian-security|http://mirror.arvancloud.ir/debian|g' \
            -e 's| bookworm-updates||g' \
            /etc/apt/sources.list.d/debian.sources; \
    fi \
    && apt-get -o Acquire::Check-Valid-Until=false update \
    && apt-get install -y --no-install-recommends \
        curl \
        default-mysql-client \
        unzip \
    && install-php-extensions \
        bcmath \
        dom \
        intl \
        mbstring \
        opcache \
        pcntl \
        pdo_mysql \
        xml \
        xmlreader \
        zip \
    && curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer \
    && apt-get purge -y --auto-remove \
    && rm -rf /var/lib/apt/lists/*

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 . .
# COPY --from=assets /app/public/build ./public/build

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 docker.arvancloud.ir/nginx:1.27-alpine AS nginx

RUN sed -i 's|https://dl-cdn.alpinelinux.org|https://mirror.arvancloud.ir/alpine|g' /etc/apk/repositories

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
