# syntax=docker/dockerfile:1

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

# ===== STAGE 2: Dependencies =====
FROM base AS deps
COPY package.json pnpm-lock.yaml ./

# Cache do pnpm store para builds mais rápidas
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
    pnpm install --frozen-lockfile

# ===== STAGE 3: Build =====
FROM deps AS build
COPY . .
RUN pnpm prisma:generate && pnpm build

# ===== STAGE 4: Production =====
FROM node:22-alpine AS production

# Cria usuário não-root
RUN addgroup --system --gid 1001 nodejs && \
    adduser --system --uid 1001 nestjs

WORKDIR /app

# Copia apenas o necessário para produção
COPY --from=build --chown=nestjs:nodejs /app/dist ./dist
COPY --from=build --chown=nestjs:nodejs /app/prisma ./prisma
COPY --from=build --chown=nestjs:nodejs /app/node_modules/.prisma ./node_modules/.prisma
COPY --from=build --chown=nestjs:nodejs /app/node_modules/@prisma ./node_modules/@prisma
COPY --from=deps --chown=nestjs:nodejs /app/node_modules ./node_modules
COPY --chown=nestjs:nodejs package.json ./

ENV NODE_ENV=production

USER nestjs

EXPOSE 3000

CMD ["node", "dist/main.js"]
