# syntax=docker/dockerfile:1

# ---------------------------------------------------------------------------
# Build stage: full dependency install (incl. dev toolchain) + production build.
# Produces the Vite client bundle (dist/) and the tsup server bundle (server/dist/).
# ---------------------------------------------------------------------------
FROM node:22-slim AS build
WORKDIR /app

# Install from the lockfile (full install — we need vite/tsup/typescript/tsx to build).
COPY package.json package-lock.json ./
RUN npm ci

# Copy the source tree and build the client and the server.
COPY . .
RUN npm run build

# ---------------------------------------------------------------------------
# Runtime stage: only production deps + the built artifacts. The server bundle
# (tsup) inlines everything except better-sqlite3, so the only runtime native
# module that must be present is better-sqlite3 (a prebuilt is fetched on npm ci).
# ---------------------------------------------------------------------------
FROM node:22-slim
ENV NODE_ENV=production
WORKDIR /app

COPY package.json package-lock.json ./
RUN npm ci --omit=dev

# Built client (serves index.html, assets, and countries.geo.json) …
COPY --from=build /app/dist ./dist
# … the compiled server bundle …
COPY --from=build /app/server/dist ./server/dist
# … and the scenario presets (loaded from disk at runtime; see findRoot()).
COPY --from=build /app/presets ./presets

# The server persists games to ./data/history.db (WAL). Kept on a volume in compose.
RUN mkdir -p ./data

# Single internal port; the client, /api, and /sse all share it.
ENV PORT=4321
EXPOSE 4321

CMD ["node", "server/dist/index.js"]
