# syntax=docker/dockerfile:1

# ===== STAGE 1: Base =====
FROM node:22-bookworm-slim AS base
RUN corepack enable && corepack prepare pnpm@latest --activate
WORKDIR /app

# ===== STAGE 2: Prod Dependencies =====
FROM base AS prod-deps
COPY package.json pnpm-lock.yaml ./
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
    pnpm install --prod --frozen-lockfile

# Generate Prisma Client in prod-deps to include engines
COPY prisma ./prisma
RUN pnpm prisma:generate

# ===== STAGE 3: Build =====
FROM base AS build
COPY package.json pnpm-lock.yaml ./
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
    pnpm install --frozen-lockfile
COPY . .
RUN pnpm prisma:generate && pnpm build

# ===== STAGE 4: Production (Distroless) =====
FROM gcr.io/distroless/nodejs22-debian12:nonroot

WORKDIR /app

# Copia apenas o necessário para produção
COPY --from=build --chown=nonroot:nonroot /app/dist ./dist
# Copy full node_modules from prod-deps (includes prisma client/engines)
COPY --from=prod-deps --chown=nonroot:nonroot /app/node_modules ./node_modules
COPY --chown=nonroot:nonroot package.json ./

ENV NODE_ENV=production

EXPOSE 3000

CMD ["dist/main.js"]
