# Corp Messenger API server image.
# Build context is the REPO ROOT (pnpm monorepo):
#   docker build -f packages/server/Dockerfile -t corp-messenger-server .
#
# Runtime env: see deploy/.env.example. The container runs pending DB
# migrations, then starts the API on :4000.
#
# NOTE (BUILD_LIST §B6d): migrations run on every boot — fine at ONE replica,
# races at two. Keep a single replica until B4e (pub/sub fanout) anyway.

FROM node:22-slim AS base
# tini = clean signal handling (SIGTERM); ca-certificates for outbound TLS (R2, web push)
RUN apt-get update && apt-get install -y --no-install-recommends tini ca-certificates openssl \
    && rm -rf /var/lib/apt/lists/*
RUN corepack enable && corepack prepare pnpm@11.13.0 --activate
WORKDIR /app

# ── build: compile TS → dist ─────────────────────────────────────────────────
FROM base AS build
# Manifests first (§B6a): the install layer stays cached until a manifest or
# the lockfile changes — source edits no longer reinstall every dependency.
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json tsconfig.base.json ./
COPY packages/server/package.json packages/server/
COPY packages/shared/package.json packages/shared/
# --frozen-lockfile (§B6b): deploys are reproducible or they fail loudly.
RUN pnpm install --frozen-lockfile --filter "@corp-messenger/server..."
COPY packages/shared packages/shared
COPY packages/server packages/server
COPY docs/FEATURE_STATUS.json docs/FEATURE_STATUS.json
# Emit-only compile (noCheck): type errors gate at `pnpm lint`, not image build.
# data/ holds the common-password list (§AM1); it must land at dist/data, where
# src/auth/passwordPolicy.ts looks for it — production refuses to start without it.
RUN cd packages/server && pnpm exec tsc -p tsconfig.build.json \
    && cp -R db/migrations dist/db/migrations \
    && cp -R data dist/data

# ── runtime: prod deps + dist only (§B6c — no tsx/TypeScript/vitest) ─────────
FROM base AS runtime
ENV NODE_ENV=production
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json ./
COPY packages/server/package.json packages/server/
COPY packages/shared/package.json packages/shared/
RUN pnpm install --frozen-lockfile --prod --filter "@corp-messenger/server..."
COPY --from=build /app/packages/server/dist packages/server/dist

# Build identity for the status endpoints (TELEMETRY_SPEC §A.3). Pass at build:
#   docker build --build-arg APP_VERSION=$(git describe --tags --always) \
#                --build-arg GIT_COMMIT=$(git rev-parse --short HEAD) ...
# In Coolify, set these as build args on the service. Unset = falls back to
# the repo-root VERSION file (copied to /app/VERSION here; src/lib/version.ts),
# then package.json / "unknown" (so a status endpoint never silently lies).
COPY VERSION ./
COPY docs/FEATURE_STATUS.json docs/FEATURE_STATUS.json
ARG APP_VERSION=
ARG GIT_COMMIT=
ENV APP_VERSION=${APP_VERSION}
ENV GIT_COMMIT=${GIT_COMMIT}

# Run as the image's unprivileged `node` user (uid 1000), not root. The code
# stays root-owned (read-only to the process); the one place it writes is the
# local attachments dir, <cwd>/../../uploads = /app/uploads (storage.ts, when
# S3_* is unset). A fresh named volume mounted there inherits this ownership;
# a volume created by an older root image does not — the self-host compose
# files fix that with their one-shot `uploads-perms` service. A
# DATA_ENCRYPTION_KEY_FILE must be readable by uid 1000.
RUN mkdir -p /app/uploads && chown node:node /app/uploads
USER node

WORKDIR /app/packages/server
EXPOSE 4000
ENTRYPOINT ["/usr/bin/tini", "--"]
# Migrations (§DD): by default each boot runs them first — one runner at a time,
# under a Postgres advisory lock, so copies starting together never race.
# MIGRATE_ON_BOOT=false skips them (a deploy that runs them as its own step).
# src/main.ts then starts API_PROCESSES copies of the API (default 1 = just
# src/index.ts). `exec` hands it tini's signals, so a stop closes sockets
# cleanly instead of being killed.
CMD ["sh", "-c", "if [ \"${MIGRATE_ON_BOOT:-true}\" != \"false\" ]; then node dist/db/migrate.js || exit 1; fi; exec node dist/src/main.js"]
