# syntax=docker/dockerfile:1
# Production image for the Teleton Rifa (Next.js 16, standalone output).
# Orchestrated by docker-compose.yml. See docs/deploy-vps.md for the full runbook.

# ── 1. deps: install ALL deps (incl dev) needed for the build ──
FROM node:20-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci

# ── 2. builder: next build -> .next/standalone ──
FROM node:20-slim AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# NEXT_PUBLIC_* are INLINED into the client bundle at build time, so they MUST be
# present here. Change any of them => rebuild. docker-compose passes these from
# .env.production. Defaults below are safe for the real raffle.
ARG NEXT_PUBLIC_APP_URL="https://rifa.teleton.pe"
ARG NEXT_PUBLIC_PAYMENT_PROVIDER="niubiz"
ARG NEXT_PUBLIC_DEMO_MODE=""
ARG NEXT_PUBLIC_TURNSTILE_SITE_KEY=""
ENV NEXT_PUBLIC_APP_URL=$NEXT_PUBLIC_APP_URL \
    NEXT_PUBLIC_PAYMENT_PROVIDER=$NEXT_PUBLIC_PAYMENT_PROVIDER \
    NEXT_PUBLIC_DEMO_MODE=$NEXT_PUBLIC_DEMO_MODE \
    NEXT_PUBLIC_TURNSTILE_SITE_KEY=$NEXT_PUBLIC_TURNSTILE_SITE_KEY \
    NEXT_TELEMETRY_DISABLED=1 \
    NODE_ENV=production
# Build-only placeholder so the build never fails validating a runtime-only value.
# The REAL DATABASE_URL is provided at RUNTIME via the container env (env_file);
# server env vars are never inlined into the bundle.
ENV DATABASE_URL="postgres://build:build@localhost:5432/build"
RUN npm run build

# ── 3. runner: minimal runtime, only the standalone server + static assets ──
FROM node:20-slim AS runner
WORKDIR /app
ENV NODE_ENV=production \
    NEXT_TELEMETRY_DISABLED=1 \
    PORT=3000 \
    HOSTNAME=0.0.0.0
RUN groupadd --system --gid 1001 nodejs \
 && useradd --system --uid 1001 --gid nodejs nextjs
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
CMD ["node", "server.js"]
