# ============================================================
# STAGE 1: Build Frontend + Backend
# ============================================================
FROM node:22-bookworm AS builder

# Install system dependencies for sharp and pdf processing
RUN apt-get update && apt-get install -y \
    python3 \
    make \
    g++ \
    gcc \
    libvips-dev \
    poppler-utils \
    pkg-config \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Install pnpm globally
RUN npm install -g pnpm@10.4.1 node-gyp

# Copy package files
COPY package.json pnpm-lock.yaml ./
COPY patches/ ./patches/

# Install dependencies
RUN pnpm install --frozen-lockfile

# Copy source code
COPY . .

# Build frontend + backend. Les dépendances de développement restent confinées
# au builder et ne sont jamais copiées dans l'image d'exécution.
RUN pnpm build

# ============================================================
# STAGE 2: Production image
# ============================================================
FROM node:22-bookworm-slim AS production

# Install runtime dependencies only
RUN apt-get update && apt-get install -y \
    poppler-utils \
    libvips42 \
    curl \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

ENV NODE_ENV=production

# Installer uniquement les dépendances d'exécution réduit fortement la taille
# de la couche exportée. Les binaires Sharp sont fournis par ses paquets
# optionnels de plateforme et ne nécessitent pas de script post-installation.
RUN npm install -g pnpm@10.4.1
COPY package.json pnpm-lock.yaml ./
COPY patches/ ./patches/
RUN pnpm install --prod --frozen-lockfile --ignore-scripts

# Copy built assets from builder (vite outputs to dist/public, esbuild to dist/)
COPY --from=builder /app/dist ./dist

# Copy drizzle migrations
COPY drizzle/ ./drizzle/
COPY drizzle.config.ts ./

# Create uploads directory
RUN mkdir -p /app/uploads

EXPOSE 3000

CMD ["node", "dist/index.js"]
