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

WORKDIR /app

# Copy package files
COPY package*.json ./

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

# Copy source code and configuration
COPY . .

# Build the SvelteKit application
RUN npm run build

# Prune dev dependencies after build
RUN npm prune --production

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

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

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

USER sveltekit

EXPOSE 5000

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

ENV NODE_ENV=production
ENV HOST=0.0.0.0
ENV PORT=5000
ENV ORIGIN=https://app.example.com

CMD ["node", "build"]
