# Build stage
FROM node:22-alpine AS builder

WORKDIR /app

# Copy package files first (better cache layer)
COPY package.json package-lock.json ./

# Install dependencies (include optional for native modules like oxc-parser)
RUN npm install --legacy-peer-deps && \
  npm cache clean --force

# Copy app source
COPY . .

# Build app with higher memory limit (prerendering is memory-intensive)
ENV NODE_OPTIONS="--max-old-space-size=4096"
RUN npm run build

# Runtime stage - use distroless for minimal size
FROM node:22-alpine

WORKDIR /app

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

# Install production dependencies only with optimizations
RUN npm install --omit=dev --legacy-peer-deps && \
  npm cache clean --force && \
  # Remove unnecessary files
  rm -rf /root/.npm /root/.cache

# Copy built app from builder
COPY --from=builder /app/.output ./.output

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

USER nodejs

EXPOSE 3000

# Set heap limit for production
ENV NODE_OPTIONS="--max-old-space-size=4096"

# Start app
CMD ["node", ".output/server/index.mjs"]
