# syntax=docker/dockerfile:1.7
#
# Generic Next.js standalone production image — used for all three
# portals (patient, doctor, admin, public site). The portal name is passed via a
# build arg so we get small, focused images per app.
#
# Build context = repo root.
# Build args:
#   APP_NAME  one of: patient-portal | doctor-portal | admin-portal | public-site
#   PORT      internal port the Next server listens on (3001/3002/3003/3004)
#
# Pre-req in this repo: every portal's next.config.mjs MUST set
#   output: 'standalone'
# so the builder can produce a self-contained server bundle.
FROM node:22-alpine AS deps
WORKDIR /app
COPY web/package.json web/package-lock.json* ./
# Workspaces: copy all per-app + per-package package.json so npm install
# resolves the workspace graph. Slow first time, fully cached after.
COPY web/apps ./apps
COPY web/packages ./packages
COPY web/turbo.json ./
COPY web/tsconfig.base.json ./
RUN find apps packages -name "node_modules" -type d -prune -exec rm -rf {} + 2>/dev/null; true
RUN npm ci --ignore-scripts

FROM node:22-alpine AS builder
ARG APP_NAME
WORKDIR /app
COPY --from=deps /app ./
# Build everything (turbo handles per-app build with shared cache)
RUN npx turbo run build --filter=@sehat/${APP_NAME}

FROM node:22-alpine AS runner
ARG APP_NAME
ARG PORT=3001
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=${PORT} \
    HOSTNAME=0.0.0.0
# Next standalone output ships a self-contained server.js + minimal node_modules
COPY --from=builder --chown=sehat:sehat /app/apps/${APP_NAME}/.next/standalone ./
COPY --from=builder --chown=sehat:sehat /app/apps/${APP_NAME}/.next/static ./apps/${APP_NAME}/.next/static
COPY --from=builder --chown=sehat:sehat /app/apps/${APP_NAME}/public ./apps/${APP_NAME}/public

HEALTHCHECK --interval=20s --timeout=4s --start-period=30s --retries=3 \
    CMD curl -fsS -o /dev/null -w "%{http_code}" http://127.0.0.1:${PORT}/ | grep -qE "^(200|307|404)$" || exit 1

USER sehat
ENTRYPOINT ["/sbin/tini", "--"]
# Next standalone server entry is at apps/<name>/server.js after the copies above
CMD ["sh", "-c", "node apps/${APP_NAME}/server.js"]
