# syntax=docker/dockerfile:1
# Multi-stage build for __APP_NAME__ (Express API serving the built Vite SPA).

# --- stage 1: build the client SPA ---
FROM node:20-bookworm-slim AS client
WORKDIR /app/client
COPY client/package*.json ./
# Reproducible from a committed package-lock.json (npm ci); falls back to npm
# install on a fresh scaffold that hasn't generated a lockfile yet.
RUN npm ci --no-audit --no-fund || npm install --no-audit --no-fund
COPY client/ ./
RUN npm run build

# --- stage 2: runtime ---
FROM node:20-bookworm-slim AS runtime
ENV NODE_ENV=production
WORKDIR /app

# backend deps only (no devDeps) — npm ci when a lockfile is committed, else install
COPY package*.json ./
RUN npm ci --omit=dev --no-audit --no-fund || npm install --omit=dev --no-audit --no-fund

# app source + the prebuilt SPA
COPY . .
COPY --from=client /app/client/dist ./client/dist

# run as non-root
RUN useradd --create-home --shell /usr/sbin/nologin appuser \
  && mkdir -p /app/data && chown -R appuser:appuser /app
USER appuser

EXPOSE 5002
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
  CMD node -e "require('http').get('http://localhost:'+(process.env.PORT||5002)+'/health',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"

# AUTO_MIGRATE=true runs db:sync + seed:rbac before boot (handy for single-tenant/dev).
CMD ["sh","-c","if [ \"$AUTO_MIGRATE\" = \"true\" ]; then node commands/sync-db.js && node commands/seed-rbac.js; fi; node server.js"]
