FROM oven/bun:alpine AS base

RUN apk update && apk add --no-cache libc6-compat

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

FROM base AS builder
WORKDIR /app
COPY . .
RUN bunx turbo prune @played/{{GAME_ID}}-web --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}}-web

## RUNNER - minimal production image

FROM base AS runner
WORKDIR /app

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

COPY --from=installer --chown=web:bunjs /app/apps/web/.output ./.output

USER web

CMD ["bun", ".output/server/index.mjs"]
