# syntax=docker/dockerfile:1

# NODE_ENV is deliberately NOT set here: with NODE_ENV=production, `npm ci`
# skips devDependencies - and vite, adapter-node and the tailwind plugin all
# live there. It is set in the runtime stage only.

# ── build SvelteKit → build/ (adapter-node) ─────────────────────────────────
FROM node:22-slim AS build
WORKDIR /app
COPY package.json package-lock.json .npmrc ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build

# ── prod-only deps ─────────────────────────────────────────────────────────
FROM node:22-slim AS prod-deps
WORKDIR /app
COPY package.json package-lock.json .npmrc ./
# --ignore-scripts: the only lifecycle hook here is `prepare` → `svelte-kit
# sync`, which needs the dev toolchain and has nothing to do at runtime.
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev --ignore-scripts

# ── runtime ────────────────────────────────────────────────────────────────
FROM node:22-slim AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY --from=prod-deps /app/node_modules ./node_modules
COPY --from=build /app/build ./build
COPY package.json ./

# adapter-node reads PORT/HOST; ORIGIN is set per-deployment in stack.env.
ENV PORT=3000
ENV HOST=0.0.0.0

USER node
EXPOSE 3000

# node:*-slim ships no curl with a working TLS stack, so Node does the probing.
# /healthz (src/routes/healthz) sits outside the Keycloak-guarded routes, so
# this keeps working once every other route requires a session.
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
  CMD node -e "fetch('http://127.0.0.1:3000/healthz').then((r) => process.exit(r.status < 500 ? 0 : 1)).catch(() => process.exit(1))"

CMD ["node", "build/index.js"]
