# Status Dashboard Server
# Multi-stage build for production deployment

# Build stage
FROM node:20-alpine AS builder

WORKDIR /app

# Install build dependencies for native modules (better-sqlite3)
RUN apk add --no-cache python3 make g++ git

# Copy package files (for standalone build, we need package.json without workspace refs)
COPY package*.json ./

# Remove workspace and link dependencies for standalone build
RUN sed -i '/"@lilith\/registry-integration":/d' package.json && \
    sed -i '/"@nestjs\/auth":/d' package.json && \
    sed -i '/"@nestjs\/bootstrap":/d' package.json && \
    sed -i '/"@typeorm\/entities":/d' package.json && \
    sed -i '/"@eslint\/config-base":/d' package.json

# Use npm for proper native module compilation
RUN npm install

# Copy source code
COPY tsconfig.json nest-cli.json ./
COPY src ./src

# Build the application
RUN npm run build

# Prune dev dependencies
RUN npm prune --production

# Production stage
FROM node:20-alpine AS production

WORKDIR /app

# Install runtime dependencies for better-sqlite3 and health checks
RUN apk add --no-cache libstdc++ curl ca-certificates && \
    update-ca-certificates

# Create non-root user for security
RUN addgroup -g 1001 -S nodejs && \
    adduser -S nestjs -u 1001 -G nodejs

# Create data directories
RUN mkdir -p /data/db /data/cache /data/certs && \
    chown -R nestjs:nodejs /data

# Copy built application from builder stage
COPY --from=builder --chown=nestjs:nodejs /app/dist ./dist
COPY --from=builder --chown=nestjs:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=nestjs:nodejs /app/package.json ./

# Switch to non-root user
USER nestjs

# Expose port
EXPOSE 5000

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

# Environment defaults
ENV NODE_ENV=production \
    PORT=5000 \
    DATABASE_PATH=/data/db/status-dashboard.db \
    CACHE_DIR=/data/cache/

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