# =============================================================================
# CONVERSATION ASSISTANT SERVER: Production Dockerfile
# =============================================================================
# Multi-stage build for NestJS server
# =============================================================================

FROM node:20-alpine AS base
WORKDIR /app

# Install dependencies for node-gyp (bcrypt)
RUN apk add --no-cache python3 make g++

# =============================================================================
# Dependencies stage
# =============================================================================
FROM base AS deps

# Copy workspace package files
COPY package*.json ./
COPY ../shared/package*.json ../shared/

# Install production dependencies only
RUN npm ci --only=production && npm cache clean --force

# =============================================================================
# Build stage
# =============================================================================
FROM base AS builder

COPY package*.json ./
COPY ../shared ../shared
RUN npm ci

# Copy source and build
COPY tsconfig*.json ./
COPY nest-cli.json ./
COPY src ./src

RUN npm run build

# =============================================================================
# Production stage
# =============================================================================
FROM node:20-alpine AS runner

WORKDIR /app

# Create non-root user
RUN addgroup --system --gid 1001 nodejs && \
    adduser --system --uid 1001 nestjs

# Copy production dependencies and built app
COPY --from=deps /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY package*.json ./

# Set ownership
RUN chown -R nestjs:nodejs /app

USER nestjs

# Expose port
EXPOSE 3100

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:3100/api/health || exit 1

# Start server
CMD ["node", "dist/main"]
