FROM oven/bun:alpine AS base

## BUILDER - prune monorepo to only what this service needs

FROM base AS builder
WORKDIR /app
COPY . .
RUN bunx turbo prune @played/{{GAME_ID}}-api-core --docker

## INSTALLER - install deps and build

FROM base AS installer
WORKDIR /app

COPY --from=builder /app/out/json/ .
COPY --from=builder /app/bun.lock ./bun.lock
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \
    --mount=type=cache,target=/root/.bun/install/cache,sharing=shared \
    bun install

COPY --from=builder /app/out/full/ .
RUN --mount=type=secret,id=env,target=/app/.env \
    ENV_PATH=/app/.env bunx turbo run build --filter=@played/{{GAME_ID}}-api-core

# Inline all imports into one file so the runner doesn't need node_modules.
RUN bun build api/core/dist/main.mjs \
    --outfile api/core/dist/main.bundled.mjs \
    --target=bun \
    --packages bundle

## RUNNER - minimal production image

FROM base AS runner
WORKDIR /app

RUN addgroup --system --gid 1001 bunjs && \
    adduser --system --uid 1001 api

# Bundle replaces dist/main.mjs at the same path so import.meta.url-based
# lookups in migrate.ts still find api/core/drizzle next to it.
COPY --from=installer --chown=api:bunjs /app/api/core/dist/main.bundled.mjs ./api/core/dist/main.mjs
COPY --from=installer --chown=api:bunjs /app/api/core/drizzle ./api/core/drizzle

USER api

CMD ["bun", "api/core/dist/main.mjs"]
