FROM composer:2.7 AS composer
WORKDIR /app
COPY aigo/ .
RUN composer install --no-dev --optimize-autoloader --no-interaction

FROM node:20-slim AS npm
ARG VITE_REVERB_APP_KEY
ARG VITE_REVERB_HOST
ARG VITE_REVERB_PORT
ARG VITE_REVERB_SCHEME
ENV VITE_REVERB_APP_KEY=$VITE_REVERB_APP_KEY
ENV VITE_REVERB_HOST=$VITE_REVERB_HOST
ENV VITE_REVERB_PORT=$VITE_REVERB_PORT
ENV VITE_REVERB_SCHEME=$VITE_REVERB_SCHEME
WORKDIR /app
COPY aigo/ .
RUN npm ci && npm run build

FROM php:8.2-apache AS runtime
# Added Acquire::Retries=3 to prevent Exit Code 100
RUN apt-get clean && apt-get update -o Acquire::Retries=3 && apt-get install -y --no-install-recommends \
        libmariadb-dev libpng-dev libjpeg-dev libfreetype-dev \
        libxml2-dev libonig-dev \
        libzip-dev libicu-dev libcurl4-openssl-dev \
    && rm -rf /var/lib/apt/lists/*

RUN docker-php-ext-install pdo_mysql mbstring bcmath xml curl gd zip intl
RUN pecl install redis && docker-php-ext-enable redis
RUN a2enmod rewrite

# 1. Copy the full base code from the npm builder first
COPY --from=npm /app /var/www/aigo

# 2. Layer the composer vendor files right into it
COPY --from=composer /app/vendor /var/www/aigo/vendor

# 3. Setup directories and permissions
RUN mkdir -p /var/www/aigo/storage/framework/{cache/sessions,cache/data,views,testing} \
    /var/www/aigo/storage/logs \
    /var/www/aigo/bootstrap/cache \
    && chown -R www-data:www-data /var/www/aigo/storage /var/www/aigo/bootstrap/cache

COPY docker/apache/000-default.conf /etc/apache2/sites-available/000-default.conf
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["apache2-foreground"]