# Production-optimized Dockerfile for Olympus Dashboard
# Supports 200+ services with high-performance requirements

# Use official Node.js runtime with Alpine for smaller image size
FROM node:18-alpine AS base

# Install system dependencies for production
RUN apk add --no-cache \
    libc6-compat \
    curl \
    ca-certificates \
    && update-ca-certificates

WORKDIR /app

# Set production environment
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1

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

# Copy package files
COPY package.json package-lock.json* ./

# Install dependencies with production optimizations
RUN npm ci --only=production --no-audit --no-fund && \
    npm cache clean --force

# === Builder stage ===
FROM base AS builder

COPY package.json package-lock.json* ./

# Install all dependencies (including dev dependencies for build)
RUN npm ci --no-audit --no-fund

# Copy source code
COPY . .

# Copy environment template for build-time configuration
COPY .env.example .env.local

# Generate Prisma client
RUN npx prisma generate

# Build the application with optimizations
RUN npm run build

# === Runner stage ===
FROM base AS runner

# Create non-root user for security
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

# Copy built application
COPY --from=builder /app/next.config.* ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json

# Copy built application files
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

# Copy Prisma schema and generated client
COPY --from=builder /app/prisma ./prisma
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
COPY --from=builder /app/node_modules/@prisma ./node_modules/@prisma

# Copy production dependencies
COPY --from=deps --chown=nextjs:nodejs /app/node_modules ./node_modules

# Create necessary directories and set permissions
RUN mkdir -p /app/logs /app/.next/cache && \
    chown -R nextjs:nodejs /app/logs /app/.next/cache

# Switch to non-root user
USER nextjs

# Health check configuration
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:3000/health || exit 1

# Expose port
EXPOSE 3000

# Production optimizations
ENV NODE_OPTIONS="--max-old-space-size=1024"
ENV HOSTNAME="0.0.0.0"

# Start the application
CMD ["node", "server.js"]