# Multi-stage build for Laravel + React application
FROM node:20-alpine AS frontend-builder

WORKDIR /app

# Copy package files
COPY package*.json ./

# Install Node dependencies
RUN npm ci

# Copy frontend source
COPY resources/ resources/
COPY public/ public/
COPY vite.config.ts ./
COPY tsconfig.json ./
COPY components.json ./
COPY eslint.config.js ./

# Build frontend assets
RUN npm run build

# PHP runtime stage
FROM php:8.3-fpm-alpine

# Install system dependencies
RUN apk add --no-cache \
    git \
    curl \
    libpng-dev \
    libxml2-dev \
    zip \
    unzip \
    oniguruma-dev \
    mysql-client \
    nginx \
    supervisor

# Install PHP extensions
RUN docker-php-ext-install \
    pdo_mysql \
    mbstring \
    exif \
    pcntl \
    bcmath \
    gd

# Install Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

# Set working directory
WORKDIR /var/www/html

# Copy application code first
COPY . .

# Install PHP dependencies after copying all files
RUN composer install --no-dev --optimize-autoloader --no-interaction

# Copy built frontend assets from builder stage
COPY --from=frontend-builder /app/public/build/ ./public/build/

# Copy nginx and supervisor configurations  
COPY docker/production/nginx.conf /etc/nginx/http.d/default.conf
COPY docker/production/supervisord.conf /etc/supervisord.conf
COPY docker/production/start-app.sh /usr/local/bin/start-app

# Set proper permissions
RUN chown -R www-data:www-data storage bootstrap/cache public/build \
    && chmod -R 755 storage bootstrap/cache \
    && chmod +x /usr/local/bin/start-app

# Expose port 80 for nginx
EXPOSE 80

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD php artisan --version || exit 1

# Start the application
CMD ["/usr/local/bin/start-app"]
