# Stage 1: Build frontend assets
# CORRECCION: 'AS' en mayúscula para evitar el warning
FROM node:20 AS frontend

WORKDIR /app

COPY package.json package-lock.json* ./
RUN npm install

COPY . .
RUN npm run build

# Stage 2: Serve the application
FROM dunglas/frankenphp:php8.3

# Install system dependencies
RUN apt-get update && apt-get install -y \
    git \
    unzip \
    zip \
    default-mysql-client \
    && apt-get clean && rm -rf /var/lib/apt/lists/*

# Install PHP extensions
# CORRECCION CRÍTICA: 
# Agregamos 'soap', 'calendar', 'dom', 'xml', 'curl' 
# Bagisto y sus dependencias (como Carbon o librerías de envíos) fallan si no están.
RUN install-php-extensions \
    pdo_mysql \
    mbstring \
    exif \
    pcntl \
    bcmath \
    gd \
    intl \
    zip \
    opcache \
    soap \
    calendar \
    dom \
    xml \
    curl

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

# Set working directory
WORKDIR /app

# Copy existing application directory contents
COPY . /app

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

# Install dependencies
# Agregamos variables para asegurar que composer no falle por memoria
ENV COMPOSER_ALLOW_SUPERUSER=1
RUN composer install --no-dev --optimize-autoloader --no-interaction

# 1. Crear estructura de carpetas explícitamente
RUN mkdir -p storage/framework/{sessions,views,cache} \
    && mkdir -p storage/logs \
    && mkdir -p bootstrap/cache

# 2. Copiar script de entrada
COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

# 3. Ajustar permisos iniciales
RUN chown -R www-data:www-data /app \
    && chmod -R 775 /app/storage \
    && chmod -R 775 /app/bootstrap/cache

# Exponer el puerto
EXPOSE 8000

# Usamos el script como punto de entrada
ENTRYPOINT ["docker-entrypoint.sh"]