# syntax=docker/dockerfile:1.6

ARG PHP_VERSION=8.3
ARG NODE_VERSION=20

############################
# Stage 1: PHP (Composer)  #
############################
FROM php:${PHP_VERSION}-fpm-alpine AS composer_build

# OS deps for building PHP extensions that Composer plugins may need
RUN set -eux; \
    apk add --no-cache git unzip icu-dev libzip-dev oniguruma-dev postgresql-dev autoconf build-base

# PHP extensions required by Laravel (build here too if scripts need them)
RUN set -eux; \
    docker-php-ext-configure zip; \
    docker-php-ext-install -j"$(nproc)" \
      pdo_mysql pdo_pgsql pgsql zip intl mbstring bcmath opcache

# Composer
ENV COMPOSER_ALLOW_SUPERUSER=1 COMPOSER_HOME=/tmp/composer
COPY --from=composer:2 /usr/bin/composer /usr/local/bin/composer

WORKDIR /app
# Install PHP deps first for better layer caching
COPY composer.json composer.lock ./
# DO NOT skip scripts — Laravel needs them (package discovery, etc.)
RUN composer install \
      --no-dev --no-interaction --prefer-dist \
      --optimize-autoloader

# Bring in the rest of the app
COPY . .

############################
# Stage 2: Frontend (Vite) #
############################
FROM node:${NODE_VERSION}-alpine AS node_build
WORKDIR /app

# Bring vendor so Vite can resolve ../../vendor/... imports (e.g., Livewire Flux CSS)
COPY --from=composer_build /app/vendor /app/vendor

# Only the files Node needs (faster context & cache)
COPY package.json package-lock.json* pnpm-lock.yaml* yarn.lock* vite.config.* ./
COPY resources ./resources
COPY public ./public
# If your Vite config imports from `resources` only, this is enough.
# If you reference other paths at build time, copy them similarly.

# Native build deps (rarely needed, but safe)
RUN apk add --no-cache python3 make g++

# Install using the appropriate lockfile
RUN set -eux; \
    if [ -f pnpm-lock.yaml ]; then corepack enable && pnpm i --frozen-lockfile; \
    elif [ -f yarn.lock ]; then corepack enable && yarn install --frozen-lockfile; \
    elif [ -f package-lock.json ]; then npm ci; \
    else npm i; fi

ENV NODE_ENV=production
# Standard Laravel vite build => outputs to public/build + manifest.json
RUN npm run build

#####################################
# Stage 3: Runtime (nginx + php-fpm)#
#####################################
FROM php:${PHP_VERSION}-fpm-alpine

# Base runtime packages
RUN set -eux; \
    apk add --no-cache nginx supervisor curl libzip icu-libs oniguruma libpq

# Build required PHP extensions in the final image (so they exist at runtime)
RUN set -eux; \
    apk add --no-cache libzip-dev icu-dev oniguruma-dev postgresql-dev autoconf build-base; \
    docker-php-ext-configure zip; \
    docker-php-ext-install -j"$(nproc)" \
      pdo_mysql pdo_pgsql pgsql zip intl mbstring bcmath opcache; \
    # Slim back down
    apk del --no-progress --purge libzip-dev icu-dev oniguruma-dev postgresql-dev autoconf build-base || true

# php.ini production + opcache tuning
RUN set -eux; \
    mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"; \
    { \
      echo "opcache.enable=1"; \
      echo "opcache.enable_cli=0"; \
      echo "opcache.memory_consumption=192"; \
      echo "opcache.max_accelerated_files=40000"; \
      echo "opcache.validate_timestamps=0"; \
      echo "realpath_cache_size=4096K"; \
      echo "realpath_cache_ttl=600"; \
    } >> "$PHP_INI_DIR/conf.d/99-opcache.ini"

# Configure PHP-FPM: pass env, listen TCP, run as nginx
RUN set -eux; \
    sed -ri 's|^;?clear_env\s*=.*|clear_env = no|g' /usr/local/etc/php-fpm.d/www.conf; \
    sed -ri 's|^listen = .*|listen = 127.0.0.1:9000|g' /usr/local/etc/php-fpm.d/www.conf; \
    sed -ri 's|^user\s*=.*|user = nginx|g' /usr/local/etc/php-fpm.d/www.conf; \
    sed -ri 's|^group\s*=.*|group = nginx|g' /usr/local/etc/php-fpm.d/www.conf; \
    { echo "ping.path = /ping"; echo "pm.status_path = /status"; echo "catch_workers_output = yes"; } >> /usr/local/etc/php-fpm.d/www.conf

# Runtime dirs
RUN set -eux; \
    mkdir -p /run/nginx /var/log/nginx /var/log/supervisor \
             /etc/nginx/conf.d /var/www/html \
             /var/cache/nginx /var/lib/nginx/tmp

WORKDIR /var/www/html

# Copy application code (without node_modules) and vendor from composer stage
COPY --from=composer_build --chown=nginx:nginx /app /var/www/html

# Copy built frontend assets (public/build with manifest.json)
COPY --from=node_build --chown=nginx:nginx /app/public/build /var/www/html/public/build

# Nginx + Supervisor configs + health + entrypoint (these must exist in your repo)
COPY ./docker/nginx.conf            /etc/nginx/nginx.conf
COPY ./docker/site.conf             /etc/nginx/conf.d/default.conf
COPY ./docker/supervisord.conf      /etc/supervisord.conf
COPY ./docker/healthcheck.sh        /usr/local/bin/healthcheck.sh
COPY ./docker/entrypoint.sh         /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/healthcheck.sh /usr/local/bin/entrypoint.sh

# Log to STDOUT/ERR
RUN set -eux; \
    ln -sf /dev/stdout /var/log/nginx/access.log; \
    ln -sf /dev/stderr /var/log/nginx/error.log

# Laravel writable dirs & permissions
RUN set -eux; \
    mkdir -p storage/framework/{cache,sessions,views} storage/logs bootstrap/cache; \
    chown -R nginx:nginx storage bootstrap/cache \
          /var/cache/nginx /var/lib/nginx /run/nginx /var/log/nginx /var/log/supervisor; \
    chmod -R ug+rwX storage bootstrap/cache

# Environment + port (ensure site.conf listens on 8080 or change EXPOSE to 80)
ENV APP_ENV=production APP_DEBUG=false APP_URL=http://localhost APP_PORT=8080
EXPOSE 8080

HEALTHCHECK --interval=30s --timeout=5s --retries=3 CMD ["/usr/local/bin/healthcheck.sh"]

# Drop root
USER nginx:nginx

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