# syntax=docker/dockerfile:1.7
#
# NestJS backend — multi-stage prod build.
# Build context = repo root.
#
# Stage 1: install deps  (cached unless package-lock changes)
# Stage 2: tsc build     (writes dist/ + dist/src/main.js)
# Stage 3: runtime       (slim, runs as non-root, healthchecked)
FROM node:22-alpine AS deps
WORKDIR /app
COPY backend/package.json backend/package-lock.json* ./
RUN npm ci --omit=dev=false --ignore-scripts

FROM node:22-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY backend/ ./
RUN npm run build
# Drop dev deps to shrink the runtime image
RUN npm prune --omit=dev

FROM node:22-alpine AS runner
RUN apk add --no-cache curl tini && \
    addgroup -g 1001 sehat && adduser -u 1001 -G sehat -D -s /sbin/nologin sehat
WORKDIR /app
ENV NODE_ENV=production \
    PORT=3000
COPY --from=builder --chown=sehat:sehat /app/node_modules ./node_modules
COPY --from=builder --chown=sehat:sehat /app/dist ./dist
COPY --from=builder --chown=sehat:sehat /app/package.json ./package.json

# Healthcheck — backend exposes the auth/me endpoint at /api/v2/auth/me;
# 401 (unauthenticated) is the healthy answer for a service that's up.
HEALTHCHECK --interval=20s --timeout=4s --start-period=30s --retries=3 \
    CMD curl -fsS -o /dev/null -w "%{http_code}" http://127.0.0.1:3000/api/v2/auth/me | grep -qE "^(200|401)$" || exit 1

USER sehat
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["node", "dist/src/main.js"]
