# Single image serving the whole application: the NestJS server (API, MCP,
# scheduler) also serves the built client, so one container is enough.

# ── Client build ──────────────────────────────────────────────────────────────
FROM node:24-slim AS client-build

WORKDIR /app

# Root lockfile + workspace manifest so npm ci can resolve the full graph
COPY package*.json ./
COPY client/package.json ./client/
RUN npm ci -w client

COPY client ./client
RUN npm run -w client build

# ── Server build ──────────────────────────────────────────────────────────────
FROM node:24-slim AS server-build

WORKDIR /app

COPY package*.json ./
COPY server/package.json ./server/
RUN npm ci -w server

COPY server/nest-cli.json ./server/
COPY server/tsconfig*.json ./server/
COPY server/src ./server/src
RUN npm run -w server build

# ── Runtime ───────────────────────────────────────────────────────────────────
FROM node:24-slim AS runtime

# Shared libraries chrome-headless-shell links against (from `ldd`), plus
# fontconfig and basic fonts for text rendering. Playwright's `--with-deps`
# would also pull in xvfb (with Mesa/LLVM) and extra font packages, which
# headless-only use doesn't need.
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    fontconfig \
    fonts-dejavu-core \
    fonts-liberation \
    libasound2 \
    libatk-bridge2.0-0 \
    libatk1.0-0 \
    libatspi2.0-0 \
    libdbus-1-3 \
    libexpat1 \
    libgbm1 \
    libglib2.0-0 \
    libnspr4 \
    libnss3 \
    libx11-6 \
    libxcb1 \
    libxcomposite1 \
    libxdamage1 \
    libxext6 \
    libxfixes3 \
    libxkbcommon0 \
    libxrandr2 \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY package*.json ./
COPY server/package.json ./server/

# Playwright's headless-only Chromium build, matching the installed Playwright
# version. All browser launches are headless, so the full desktop Chromium
# (GTK, Mesa/LLVM, icon themes) isn't needed.
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
RUN npm ci --omit=dev -w server \
    && npx playwright install --only-shell chromium \
    && npm cache clean --force

COPY --from=server-build /app/server/dist ./dist
COPY --from=client-build /app/client/dist ./client

# Serve the built client at / (see server/src/common/client-static.ts)
ENV CLIENT_DIR=client

# Runtime directories (keys and SQLite DB mounted via volumes)
RUN mkdir -p data

EXPOSE 3000

CMD ["node", "dist/main"]
