# ── stage 1: dependencies ──────────────────────────────────────────────────────
FROM node:22-alpine AS deps

WORKDIR /app
RUN apk add --no-cache openssl
COPY package.json package-lock.json ./
RUN npm ci --legacy-peer-deps

# ── stage 2: build ─────────────────────────────────────────────────────────────
FROM node:22-alpine AS builder

WORKDIR /app
RUN apk add --no-cache openssl
# NOTE: NEXTAUTH_SECRET is a build-time placeholder only — never expose real secrets in ARG/ENV
ENV DATABASE_URL=postgresql://fifa_user:change_me@localhost:5432/fifa2026
ENV NEXTAUTH_SECRET=build-time-placeholder
ENV NEXTAUTH_URL=https://2026fifa.wooo.work
ENV ANALYTICS_BACKEND_URL=http://fifa2026-backend:8000
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npx prisma generate
RUN npm run build

# ── stage 3: runtime (hardened) ────────────────────────────────────────────────
FROM node:22-alpine AS runtime

WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000

# Install openssl first (needed at runtime)
RUN apk add --no-cache openssl

# Security: create non-root user BEFORE removing shell
RUN addgroup -g 1001 -S nodejs \
    && adduser  -S nextjs -u 1001 -G nodejs

COPY --from=builder /app/public ./public
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
COPY --from=builder /app/prisma ./prisma

# Lock down ownership
RUN chown -R nextjs:nodejs /app \
    && chmod -R o-rwx /app

# Security: remove tools that can be used to download/execute malware
# MUST happen AFTER all RUN commands that need a shell
RUN rm -f /usr/bin/wget /usr/bin/curl \
          /usr/local/bin/npm /usr/local/bin/npx \
    && true

# Drop all privileges – run as nextjs (uid 1001)
USER nextjs

EXPOSE 3000

# Use node directly (not npm) to avoid extra shell processes
CMD ["node", "node_modules/.bin/next", "start", "-p", "3000"]
