# =========================
# 1. Composer Dependencies
# =========================
FROM composer:2 AS vendor
WORKDIR /var/www/html

# Copy composer files and install dependencies without artisan scripts
COPY composer.json composer.lock ./
RUN composer install --no-dev --optimize-autoloader --no-interaction --no-progress --no-scripts

# =========================
# 2. Node (Vite build)
# =========================
FROM node:18 AS node_builder
WORKDIR /var/www/html

# Copy package.json and package-lock.json first for caching
COPY package*.json ./

# Install dependencies (skip postinstall initially to avoid build-icons.js errors)
RUN npm install --ignore-scripts --legacy-peer-deps

# Install required SCSS compiler
RUN npm install -D sass-embedded

# Copy only frontend-related source files
COPY resources ./resources
COPY vite.config.* ./
COPY tailwind.config.* ./
COPY postcss.config.* ./

# Remove old build folder if exists
RUN rm -rf public/build

# Run icon build script and Vite build
RUN npm run build:icons && npm run build

# =========================
# 3. PHP Runtime (Final App)
# =========================
FROM php:8.2-fpm AS app
WORKDIR /var/www/html

# Install PHP extensions
RUN apt-get update && apt-get install -y \
    libpq-dev libzip-dev unzip git curl \
    && docker-php-ext-install pdo pdo_pgsql zip \
    && rm -rf /var/lib/apt/lists/*

# Copy Composer binary into container
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer

# Copy vendor deps from Composer stage
COPY --from=vendor /var/www/html/vendor ./vendor

# Copy Laravel source code
COPY . .

# Copy built frontend assets from Node stage
COPY --from=node_builder /var/www/html/public/build ./public/build

# Run composer scripts now that artisan exists
RUN composer run-script post-autoload-dump

# Fix permissions for Laravel
RUN chown -R www-data:www-data storage bootstrap/cache \
    && chmod -R 775 storage bootstrap/cache

EXPOSE 9000
CMD ["php-fpm"]
