# syntax=docker/dockerfile:1
# Build from monorepo root: docker build -f apps/edr-payment-api/Dockerfile .
FROM node:24.15.0-alpine AS base
RUN apk add --no-cache libc6-compat
# Store pnpm's content-addressable store under PNPM_HOME so the BuildKit
# `--mount=type=cache,target=/pnpm/store` cache actually persists deps across builds.
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable
WORKDIR /app
FROM base AS pruner
COPY . .
RUN pnpm dlx turbo prune "@edr/payment-api" --docker
FROM base AS installer
COPY --from=pruner /app/out/json/ .
COPY --from=pruner /app/out/pnpm-lock.yaml ./pnpm-lock.yaml
RUN --mount=type=secret,id=npmrc,target=./.npmrc,required=false \
    --mount=type=cache,id=pnpm,target=/pnpm/store \
    pnpm install --frozen-lockfile
FROM base AS builder
COPY --from=installer /app/ .
COPY --from=pruner /app/out/full/ .
RUN pnpm turbo build --filter="@edr/payment-api..."
FROM base AS deployer
COPY --from=builder /app/ .
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
    pnpm deploy --filter="@edr/payment-api" --prod --legacy --ignore-scripts /deploy

# --- Migration image: built in CI, run as a one-shot `docker run --rm --env-file ...`
# against the real DB, as its own gated step *before* the app image is built/deployed.
# The runner below only ever runs `node dist/main.js` — migrations happen here, not there.
FROM deployer AS migration
WORKDIR /deploy
CMD ["node", "dist/scripts/migrate.js"]

FROM node:24.15.0-alpine AS runner
RUN apk add --no-cache libc6-compat
ENV NODE_ENV=production
WORKDIR /app
RUN addgroup --system --gid 1001 nodejs \
    && adduser --system --uid 1001 --ingroup nodejs nestjs
COPY --from=deployer --chown=nestjs:nodejs /deploy .
USER nestjs
EXPOSE 3008
CMD ["node", "dist/main.js"]
