# syntax=docker/dockerfile:1

# Build stage for Node.js assets
FROM node:20-alpine AS node-builder

WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies with clean install
RUN npm ci --prefer-offline --no-audit

# Copy source files needed for build
COPY resources ./resources
COPY public ./public
COPY vite.config.js postcss.config.* tailwind.config.* ./

# Build assets
RUN npm run build

# PHP dependencies stage
FROM php:8.2-cli-alpine AS composer-builder

WORKDIR /app

# Copy composer files
COPY composer.json composer.lock ./

RUN apk add --no-cache \
    git \
    unzip \
    libzip \
    freetype \
    libjpeg-turbo \
    libpng && \
    apk add --no-cache --virtual .build-deps \
    $PHPIZE_DEPS \
    libzip-dev \
    freetype-dev \
    libjpeg-turbo-dev \
    libpng-dev && \
    docker-php-ext-configure gd --with-freetype --with-jpeg && \
    docker-php-ext-install -j$(nproc) gd zip && \
    apk del .build-deps && \
    rm -rf /tmp/* /var/cache/apk/*

RUN php -r "copy('https://getcomposer.org/installer','composer-setup.php');" && \
    php composer-setup.php --install-dir=/usr/local/bin --filename=composer && \
    rm composer-setup.php

# Install dependencies without dev packages
RUN composer install \
    --no-dev \
    --no-interaction \
    --no-progress \
    --no-scripts \
    --prefer-dist \
    --optimize-autoloader

# Final production stage
FROM php:8.2-fpm-alpine

# Install system dependencies and PHP extensions
RUN apk add --no-cache \
    bash \
    freetype \
    libjpeg-turbo \
    libpng \
    libzip \
    nginx \
    oniguruma \
    supervisor \
    && apk add --no-cache --virtual .build-deps \
    $PHPIZE_DEPS \
    freetype-dev \
    libjpeg-turbo-dev \
    libpng-dev \
    libzip-dev \
    oniguruma-dev \
    && docker-php-ext-configure gd \
    --with-freetype \
    --with-jpeg \
    && docker-php-ext-install -j$(nproc) \
    bcmath \
    exif \
    gd \
    mbstring \
    opcache \
    pdo_mysql \
    zip \
    && pecl install redis \
    && docker-php-ext-enable redis \
    && apk del .build-deps \
    && rm -rf /tmp/* /var/cache/apk/*

# Configure PHP for production
COPY <<EOF /usr/local/etc/php/conf.d/production.ini
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=20000
opcache.validate_timestamps=0
opcache.save_comments=1
opcache.fast_shutdown=1
expose_php=0
memory_limit=1024M
upload_max_filesize=50M
post_max_size=50M
max_execution_time=300
EOF

# Create application user
RUN addgroup -g 1000 appuser && \
    adduser -u 1000 -G appuser -s /bin/sh -D appuser

WORKDIR /var/www/html

# Copy application files
COPY --chown=appuser:appuser . .
COPY --from=composer-builder --chown=appuser:appuser /app/vendor ./vendor
COPY --from=node-builder --chown=appuser:appuser /app/public/build ./public/build

# Set permissions
RUN chown -R appuser:appuser /var/www/html && \
    chmod -R 755 /var/www/html/storage /var/www/html/bootstrap/cache && \
    ln -s /var/www/html/storage/app/public /var/www/html/public/storage

# Configure Nginx
COPY <<EOF /etc/nginx/http.d/default.conf
server {
    listen 80;
    server_name _;
    root /var/www/html/public;
    index index.php;

    client_max_body_size 50M;

    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }

    location ~ \\.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_connect_timeout 60;
        fastcgi_send_timeout 600;
        fastcgi_read_timeout 600;
    }

    location ~ /\\.(?!well-known).* {
        deny all;
    }
}
EOF

# Tune PHP-FPM pool
COPY <<EOF /usr/local/etc/php-fpm.d/zz-overrides.conf
[www]
pm = dynamic
pm.max_children = 40
pm.start_servers = 4
pm.min_spare_servers = 4
pm.max_spare_servers = 10
pm.max_requests = 500
catch_workers_output = yes
request_terminate_timeout = 120s
EOF

# Configure Supervisor
COPY <<EOF /etc/supervisord.conf
[supervisord]
nodaemon=true
user=root
logfile=/dev/stdout
logfile_maxbytes=0
pidfile=/var/run/supervisord.pid

[program:php-fpm]
command=php-fpm
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
autorestart=true

[program:nginx]
command=nginx -g 'daemon off;'
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
autorestart=true

[program:queue-worker]
command=php /var/www/html/artisan queue:work --sleep=3 --tries=3 --max-time=3600
user=appuser
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
autorestart=true
stopwaitsecs=3600
EOF

USER root

EXPOSE 80

HEALTHCHECK --interval=30s --timeout=3s --start-period=40s \
    CMD php artisan schedule:list || exit 1

CMD ["/usr/bin/supervisord", "-c", "/etc/supervisord.conf"]
