FROM node:24-alpine AS base

# ── Stage 1: install deps ─────────────────────────────────────────────────────
FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
# A High or Critical advisory in a runtime dependency fails the image (F45). Dev tooling is not shipped,
# so it is excluded. Moderate advisories do not block; review them with a full `npm audit`.
RUN npm audit --omit=dev --audit-level=high

# ── Stage 2: source shared by test and build ─────────────────────────────────
FROM base AS source
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# ── Stage 3a: test ────────────────────────────────────────────────────────────
# Tests run here deliberately: a red suite fails the image build, matching
# solvway-customer-portal. CI (.gitea/workflows/ci.yml) runs no separate portal test step,
# so this stage is the portal's test gate there.
# .dockerignore must therefore NOT exclude test/ or *.test.ts(x) — vitest.config.ts
# aliases `server-only` to test/stub-empty.ts.
# BuildKit runs this stage in parallel with builder, and builds only stages the target needs: the
# runner's COPY of .tests-passed is what keeps this suite a gate. Do not remove it.
FROM source AS test
# ci-runs-repo-checks: an ESLint error fails the image like a red test (warnings do not).
RUN npm run lint && npm run test && touch .tests-passed

# ── Stage 3b: build ───────────────────────────────────────────────────────────
FROM source AS builder
# Delete Next's build cache in the same RUN so it never lands in a committed layer. Nothing reads it: the
# build starts from a clean .next (.dockerignore) and the runner copies only standalone/, static/ and public/.
# Left in, Turbopack's churning .sst store made Docker fail to apply the layer (main run 5980:
# "failed to Lchown .../.next/cache/turbopack/...sst: no such file").
RUN npm run build && rm -rf .next/cache

# ── Stage 4: runtime image ────────────────────────────────────────────────────
FROM base AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"

RUN addgroup --system --gid 1001 nodejs \
 && adduser  --system --uid 1001 nextjs

COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static    ./.next/static
COPY --from=builder --chown=nextjs:nodejs /app/public          ./public
# Depends on the test stage so a red suite fails the image (see Stage 3a).
COPY --from=test /app/.tests-passed /tmp/.tests-passed

USER nextjs
EXPOSE 3000

# Supply MOBILE_API_BASE_URL, MOBILE_API_KEY and SESSION_COOKIE_NAME at runtime
# via -e flags / k8s env — never bake secrets into the image
CMD ["node", "server.js"]
