# Multi-stage Dockerfile for API Service

# Stage 1: Dependencies
FROM node:20-alpine AS deps
WORKDIR /app

# Install pnpm
RUN npm install -g pnpm@10.11.0

# Copy workspace configuration
COPY pnpm-workspace.yaml package.json pnpm-lock.yaml ./

# Copy package.json files
COPY apps/api-service/package.json ./apps/api-service/
COPY packages/database/package.json ./packages/database/

# Install dependencies
RUN pnpm install --frozen-lockfile

# Stage 2: Builder
FROM node:20-alpine AS builder
WORKDIR /app

# Install pnpm
RUN npm install -g pnpm@10.11.0

# Copy dependencies from deps stage
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/apps/api-service/node_modules ./apps/api-service/node_modules
COPY --from=deps /app/packages/database/node_modules ./packages/database/node_modules

# Copy workspace files
COPY pnpm-workspace.yaml package.json pnpm-lock.yaml ./

# Copy database package
COPY packages/database ./packages/database

# Copy API service source (exclude .env - it's for local dev only)
COPY apps/api-service/package.json ./apps/api-service/
COPY apps/api-service/tsconfig.json ./apps/api-service/
COPY apps/api-service/src ./apps/api-service/src

# Set working directory to API service
WORKDIR /app/apps/api-service

# Build TypeScript
RUN pnpm build

# Stage 3: Production Runner
FROM node:20-alpine AS production
WORKDIR /app

# Install pnpm
RUN npm install -g pnpm@10.11.0

ENV NODE_ENV=production

# Create non-root user
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 apiuser

# Copy workspace configuration
COPY --from=builder /app/pnpm-workspace.yaml ./
COPY --from=builder /app/package.json ./
COPY --from=builder /app/pnpm-lock.yaml ./

# Copy database package
COPY --from=builder /app/packages/database ./packages/database

# Copy built API service
COPY --from=builder --chown=apiuser:nodejs /app/apps/api-service/dist ./apps/api-service/dist
COPY --from=builder /app/apps/api-service/package.json ./apps/api-service/

# Copy node_modules for runtime
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/apps/api-service/node_modules ./apps/api-service/node_modules
COPY --from=builder /app/packages/database/node_modules ./packages/database/node_modules

# Create directories for logs and data
RUN mkdir -p /app/apps/api-service/logs /app/results /app/uploads/temp
RUN chown -R apiuser:nodejs /app/apps/api-service/logs /app/results /app/uploads

USER apiuser

EXPOSE 3000

WORKDIR /app/apps/api-service

# Run production build
CMD ["node", "dist/server.js"]
