# Multi-stage build for optimized production image
# Stage 1: Build the application
FROM node:20-alpine AS builder

# Set working directory
WORKDIR /app

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

# Install dependencies
# `npm install` instead of `npm ci` to skip strict platform-pinned optional deps
# (lock file references AIX/ppc64 esbuild binary that doesn't apply on linux/x64).
RUN npm install --no-audit --no-fund

# Copy source code
COPY . .

# Accept env vars as build args
ARG VITE_API_URL
ARG VITE_KEYCLOAK_URL

# Create .env file from build args (if provided)
# All traffic (API + Keycloak auth) is routed through VITE_API_URL;
# VITE_KEYCLOAK_URL overrides the Keycloak base (same-origin /auth proxy)
RUN touch .env; \
    if [ -n "$VITE_API_URL" ]; then \
      echo "VITE_API_URL=${VITE_API_URL}" >> .env; \
    fi; \
    if [ -n "$VITE_KEYCLOAK_URL" ]; then \
      echo "VITE_KEYCLOAK_URL=${VITE_KEYCLOAK_URL}" >> .env; \
    fi

# Build the application
RUN npm run build

# Stage 2: Production image with Nginx
FROM nginx:alpine

# Copy custom nginx configuration
COPY nginx.conf /etc/nginx/conf.d/default.conf

# Copy SSL cert (self-signed for local HTTPS, required by Keycloak PKCE)
COPY ssl/server.crt /etc/nginx/ssl/server.crt
COPY ssl/server.key /etc/nginx/ssl/server.key

# Copy built assets from builder stage
COPY --from=builder /app/dist /usr/share/nginx/html

# Expose ports
EXPOSE 80 443

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

# Start nginx
CMD ["nginx", "-g", "daemon off;"]
