# =============================================================================
# tOS API - Multi-Stage Docker Build
# =============================================================================
# Optimiert fuer pnpm Monorepo mit Prisma ORM
#
# Build:   docker build -f apps/api/Dockerfile -t tos-api .
# Run:     docker run -p 3001:3001 --env-file .env tos-api
# =============================================================================

# ---------------------------------------------------------------------------
# Stage 1: Base - Node.js mit pnpm
# ---------------------------------------------------------------------------
FROM node:20-alpine AS base
RUN corepack enable && corepack prepare pnpm@9.15.0 --activate

# ---------------------------------------------------------------------------
# Stage 2: Builder - Dependencies installieren und kompilieren
# ---------------------------------------------------------------------------
FROM base AS builder
WORKDIR /app

# Kopiere Workspace-Konfiguration (fuer pnpm Monorepo-Aufloesung)
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml ./

# Kopiere Shared Package (wird von der API als Dependency referenziert)
COPY packages/ ./packages/

# Kopiere API-Quellcode
COPY apps/api/ ./apps/api/

# Installiere alle Dependencies (frozen-lockfile fuer reproduzierbare Builds)
RUN pnpm install --frozen-lockfile

# Baue zuerst das Shared Package (Dependency der API)
RUN pnpm --filter @tos/shared build

# Generiere Prisma Client (benoetigt fuer den Build)
RUN pnpm --filter @tos/api exec prisma generate

# Baue die API
RUN pnpm --filter @tos/api build

# ---------------------------------------------------------------------------
# Stage 3: Runner - Schlankes Production Image
# ---------------------------------------------------------------------------
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production

# Kopiere Build-Artefakte
COPY --from=builder /app/apps/api/dist ./dist
COPY --from=builder /app/apps/api/prisma ./prisma
COPY --from=builder /app/apps/api/package.json ./package.json

# Kopiere node_modules (API-spezifisch + hoisted)
COPY --from=builder /app/apps/api/node_modules ./node_modules
# Kopiere Prisma Client (plattform-spezifische Binaries)
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
COPY --from=builder /app/node_modules/@prisma ./node_modules/@prisma

# Sicherheit: Nicht als root ausfuehren
USER node

EXPOSE 3001

# Beim Start: Zuerst Datenbankmigrationen anwenden, dann API starten
CMD ["sh", "-c", "npx prisma migrate deploy && node dist/main.js"]
