# SIOP V2 — image API (NestJS + Prisma).
# Contexte de build : RACINE du monorepo (docker build -f apps/api/Dockerfile .)
# Étage 1 : dépendances + builds ; étage 2 : runtime minimal (node:24-slim).

FROM node:24-slim AS builder
RUN corepack enable
WORKDIR /repo

# Manifestes d'abord (cache de couche pour pnpm install)
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY packages/shared/package.json packages/shared/package.json
COPY apps/api/package.json apps/api/package.json
RUN pnpm install --frozen-lockfile --filter @siop/api --filter @siop/shared

COPY packages/shared packages/shared
COPY apps/api apps/api
RUN pnpm --filter @siop/shared build \
  && pnpm --filter @siop/api prisma:generate \
  && pnpm --filter @siop/api build \
  && pnpm --filter @siop/api deploy --legacy --prod /out
# Client Prisma regénéré DANS l'arborescence déployée (node_modules à plat)
RUN cd /out && ./node_modules/.bin/prisma generate \
  && cp -r /repo/apps/api/dist /out/dist

FROM node:24-slim
# openssl : requis par les moteurs Prisma
RUN apt-get update \
  && apt-get install -y --no-install-recommends openssl ca-certificates \
  && rm -rf /var/lib/apt/lists/*
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder --chown=node:node /out /app
COPY --chown=node:node apps/api/docker-entrypoint.sh ./docker-entrypoint.sh
RUN chmod +x docker-entrypoint.sh
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=20s --retries=3 \
  CMD node -e "fetch('http://localhost:3000/health').then((r)=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
ENTRYPOINT ["./docker-entrypoint.sh"]
