# ============================================
# Stage 1: Dependencies
# ============================================
FROM node:24-alpine AS deps
WORKDIR /app

COPY package.json package-lock.json ./
RUN npm ci

# ============================================
# Stage 2: Build
# ============================================
FROM node:24-alpine AS builder
WORKDIR /app

COPY --from=deps /app/node_modules ./node_modules
COPY . .

RUN npm run build

# ============================================
# Stage 3: Production
# ============================================
FROM node:24-alpine AS runner
WORKDIR /app

# Set runtime defaults (override with docker run -e or K8s configmap)
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1

# Create non-root user
RUN addgroup --system --gid 1001 nodejs && \
    adduser --system --uid 1001 nextjs

# Copy standalone build output
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

# Switch to non-root user
USER nextjs

EXPOSE 3000

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:3000/api/config || exit 1

# Raise the Node HTTP header size limit (default 16KB) so the Next server does
# not reject real users with 431 (Request Header Fields Too Large) when their
# browser accumulates a large cookie jar on the shared *.redtag.ca domain
# (auth, analytics/Datadog, consent, session ids, etc.).
ENV NODE_OPTIONS=--max-http-header-size=65536

ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
CMD ["node", "server.js"]
