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/platform-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 \
    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/platform-api-core

## RUNNER — minimal production image

FROM base AS runner
WORKDIR /app

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

# Copy the full pruned+built workspace — symlinks, package.json exports maps
# and built dist/ dirs are all in the right place without manual cherry-picking.
# Notably, packages/platform/sql/ comes along, which migrate.ts resolves at
# runtime via import.meta.resolve("@played/platform/package.json").
COPY --from=installer --chown=api:bunjs /app .

USER api

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