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

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies (including devDependencies for build)
RUN npm ci

# Copy source code and configuration
COPY . .

# Build the SvelteKit application
# Note: PUBLIC_* vars must be set at build time for SvelteKit
ARG PUBLIC_KRATOS_URL=https://auth.example.com
ENV PUBLIC_KRATOS_URL=$PUBLIC_KRATOS_URL

RUN npm run build

# Prune dev dependencies
RUN npm prune --production

# ====================================
# Production Stage
# ====================================
FROM node:20-alpine

# Install curl for health checks
RUN apk add --no-cache curl

# Set working directory
WORKDIR /app

# Copy built application from builder
COPY --from=builder /app/build ./build
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json

# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
    adduser -S sveltekit -u 1001 && \
    chown -R sveltekit:nodejs /app

# Switch to non-root user
USER sveltekit

# Expose port 3000
EXPOSE 3000

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

# Set environment variable for production
ENV NODE_ENV=production

# Start the application
CMD ["node", "build"]
