# syntax=docker/dockerfile:1
FROM node:20-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci || npm install

FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1
RUN npm run build

FROM node:20-alpine AS runner
WORKDIR /app
# Clear the fixable HIGH CVEs baked into the base image (issues #51, #60):
#   - OS packages: `apk upgrade` pulls the patched libcrypto3/libssl3 (openssl)
#     revisions from the pinned Alpine branch. c-ares is no longer a fixable
#     finding on the current base (Alpine 3.23) — it is not installed as an apk
#     package and Node's bundled copy is already past the fix.
#   - The globally-installed npm CLI ships its OWN vulnerable dependencies under
#     /usr/local/lib/node_modules/npm (cross-spawn 7.0.3, node-tar 6.2.1, glob,
#     minimatch, sigstore). These are NOT app dependencies. The standalone server
#     runs `node server.js` and never needs npm at runtime, so removing the
#     bundled npm CLI clears all of those HIGH findings at the source.
RUN apk upgrade --no-cache libcrypto3 libssl3 \
 && rm -rf /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx
ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1
RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs

# Next.js standalone output bundles only what is needed to run.
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs
EXPOSE 3000
ENV PORT=3000 HOSTNAME=0.0.0.0

# --- Build provenance (issue #22): OCI labels + inspectable runtime env. -----
ARG GIT_COMMIT=unknown
ARG BUILD_ID=local
ARG VERSION=dev
ARG BUILD_DATE=unknown
ENV GIT_COMMIT=$GIT_COMMIT BUILD=$BUILD_ID BUILD_VERSION=$VERSION BUILD_DATE=$BUILD_DATE
LABEL org.opencontainers.image.revision=$GIT_COMMIT \
      org.opencontainers.image.version=$VERSION \
      org.opencontainers.image.created=$BUILD_DATE

# Runtime env (compose): CP_URL, CP_ADMIN_TOKEN — server-side only, never in the bundle.
CMD ["node", "server.js"]
