# ==============================================================================
# Multi-stage Dockerfile for Coolify & Containerized Environments
# ==============================================================================

# ------------------------------------------------------------------------------
# Stage 1: Build Stage
# ------------------------------------------------------------------------------
FROM node:20-alpine AS builder

WORKDIR /app

# Copy package manifests
COPY package*.json ./

# Install dependencies needed for vite & esbuild build
RUN npm install

# Copy full application source code
COPY . .

# Run production build (vite client build + esbuild server compilation)
RUN npm run build

# ------------------------------------------------------------------------------
# Stage 2: Production Runner Stage
# ------------------------------------------------------------------------------
FROM node:20-alpine AS runner

WORKDIR /app

ENV NODE_ENV=production
ENV PORT=7000
ENV DATA_PATH=/app/data/portal-data.json

# Copy package manifests
COPY package*.json ./

# Install production dependencies only
RUN npm install --omit=dev && npm cache clean --force

# Copy compiled distribution output from builder stage
COPY --from=builder /app/dist ./dist

# Create persistent data directory
RUN mkdir -p /app/data

# Healthcheck to verify Express server status
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:7000/api/health || exit 1

# Start production application server
CMD ["node", "dist/server.cjs"]
