# ---- Composer Stage ----
# Use the official Composer image to install dependencies
FROM composer:2 AS composer_builder

WORKDIR /app

# Copy only dependency files to leverage layer cache
COPY composer.json composer.lock ./

# Install dependencies without dev requirements and optimize autoloader
RUN composer install --no-dev --no-interaction --optimize-autoloader

# ---- Final Stage ----
# Use an official php-fpm-alpine image for a small production environment
FROM php:8.2-fpm-alpine

WORKDIR /app

# Create a non-root user
RUN addgroup -S app && adduser -S app -G app

# Copy installed dependencies from the composer stage, owned by the app user.
# vendor/ lives inside /app, so it must carry --chown too (the old recursive
# `chown -R .` covered it; without --chown it would stay root-owned).
COPY --chown=app:app --from=composer_builder /app/vendor/ ./vendor/

# Copy the application source code, already owned by the app user.
# COPY --chown avoids a following `chown -R`, which would rewrite vendor +
# source into a SECOND layer (stored twice — pure image bloat).
COPY --chown=app:app . .

# Own the WORKDIR itself (COPY --chown only owns the copied entries) so the
# app user can write here at runtime (e.g. Laravel/Symfony storage,
# bootstrap/cache). Create + chmod framework dirs in your app if needed.
RUN chown app:app .

# Switch to the non-root user
USER app

# Expose the port FPM listens on
EXPOSE 9000

# The CMD is provided by the base php-fpm image, which starts the FPM process.
