# syntax=docker/dockerfile:1.7
# Multi-stage Dockerfile for SupplierPulse (Next.js 16 App Router).
# Target: Azure Container Apps. See DEPLOYMENT.md for context.
#
# Stages:
#   1. deps    — install full dependency tree against the lockfile.
#   2. builder — produce the Next.js production output.
#   3. runner  — minimal runtime image, non-root, no secrets baked in.
#
# Build:   docker build -t supplierpulse-web:local .
# Run:     docker run --rm -p 3000:3000 --env-file .env.local supplierpulse-web:local

ARG NODE_VERSION=24-bookworm-slim

# -----------------------------------------------------------------------------
# 1) deps
# -----------------------------------------------------------------------------
FROM node:${NODE_VERSION} AS deps
WORKDIR /app

# Avoid contacting telemetry endpoints during build.
ENV NEXT_TELEMETRY_DISABLED=1
ENV CI=true

# Copy lockfile + manifest only so this layer caches across source changes.
COPY package.json package-lock.json ./
RUN npm ci --no-audit --no-fund

# -----------------------------------------------------------------------------
# 2) builder
# -----------------------------------------------------------------------------
FROM node:${NODE_VERSION} AS builder
WORKDIR /app

ENV NEXT_TELEMETRY_DISABLED=1
ENV CI=true
ENV NODE_ENV=production

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

# Build runs the service-worker version injection followed by `next build`.
# Public env vars must be available at build time for Next.js bundling.
RUN npm run build

# Drop dev dependencies for the runtime stage.
RUN npm prune --omit=dev

# -----------------------------------------------------------------------------
# 3) runner
# -----------------------------------------------------------------------------
FROM node:${NODE_VERSION} AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=3000
ENV HOSTNAME=0.0.0.0

# Create a dedicated, non-root runtime user.
RUN groupadd --system --gid 1001 nodejs \
 && useradd  --system --uid 1001 --gid nodejs --home /app nextjs

# Copy production assets only. Service-worker file is in `public/`.
COPY --chown=nextjs:nodejs --from=builder /app/.next         ./.next
COPY --chown=nextjs:nodejs --from=builder /app/public        ./public
COPY --chown=nextjs:nodejs --from=builder /app/node_modules  ./node_modules
COPY --chown=nextjs:nodejs --from=builder /app/package.json  ./package.json
COPY --chown=nextjs:nodejs --from=builder /app/next.config.mjs ./next.config.mjs

USER nextjs

EXPOSE 3000

# `next start` reads PORT/HOSTNAME from the environment.
CMD ["npx", "--no-install", "next", "start"]
