# Base image with Bun
FROM oven/bun:1.4.2 AS base

# Install turbo CLI globally
FROM base AS turbo-cli
# Same turbo as the root package.json; an unpinned one changes the pruned
# lockfile under our feet.
RUN bun add -g turbo@2.9.3

# Builder stage - prune API workspace
FROM turbo-cli AS builder
WORKDIR /app
COPY . .
RUN turbo prune @midday/api --docker

# Installer stage - install deps and build
FROM base AS installer
WORKDIR /app

# Install dependencies
COPY --from=builder /app/out/json/ .
COPY bunfig.toml .
# Install strictly from the lockfile. turbo prune (2.9.3 and 2.11.4 alike)
# writes bun.lock's tarball entries -- xlsx from cdn.sheetjs.com -- with an
# extra "" field bun cannot parse; bun then ignored the whole lockfile and
# resolved every dependency afresh on each build. The sed repairs that one
# shape (a no-op once turbo fixes it); --frozen-lockfile fails the build if
# the lockfile and the package.json files ever disagree.
RUN sed -E -i 's/(\["[^"]+@https?:\/\/[^"]+"), "", /\1, /' bun.lock \
  && bun install --frozen-lockfile

# Copy full source
COPY --from=builder /app/out/full/ .

# Build the mcp-apps package (produces self-contained HTML files)
RUN cd packages/mcp-apps && bun run build

# Runner stage - clean image
FROM oven/bun:1.4.2 AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV PORT=8080

# Copy only what's needed at runtime
COPY --from=installer /app/node_modules ./node_modules
COPY --from=installer /app/apps/api ./apps/api
COPY --from=installer /app/packages ./packages
COPY --from=installer /app/package.json ./package.json

# Carry the git SHA into the runtime container (stamped by CI before `railway up`)
COPY --from=builder /app/.git-commit-sha /tmp/git-sha.txt
COPY --from=builder /app/scripts/docker-entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh

WORKDIR /app/apps/api

# R8 (audit D-03): not root. `bun` (uid 1000) comes with oven/bun; the
# files above stay root-owned and read-only to it, and compose runs the
# container with a read-only root and /tmp in memory.
USER bun

EXPOSE 8080

ENTRYPOINT ["/app/entrypoint.sh"]
CMD ["bun", "src/index.ts"]
