# Multi-stage Dockerfile for Node.js applications
# Generated by AIWG deploy-gen
# Research: REF-001 BP-8 - Containerized Deployment

# =============================================================================
# Stage 1: Dependencies
# =============================================================================
FROM node:{{NODE_VERSION}}-alpine AS deps

WORKDIR /app

# Copy package files
COPY package*.json ./
COPY yarn.lock* ./
COPY pnpm-lock.yaml* ./

# Install dependencies based on lockfile
RUN \
  if [ -f yarn.lock ]; then yarn install --frozen-lockfile; \
  elif [ -f pnpm-lock.yaml ]; then npm install -g pnpm && pnpm install --frozen-lockfile; \
  elif [ -f package-lock.json ]; then npm ci; \
  else npm install; \
  fi

# =============================================================================
# Stage 2: Build (if needed)
# =============================================================================
FROM node:{{NODE_VERSION}}-alpine AS builder

WORKDIR /app

# Copy dependencies
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Build if build script exists
RUN \
  if grep -q '"build"' package.json; then \
    npm run build; \
  fi

# =============================================================================
# Stage 3: Production
# =============================================================================
FROM node:{{NODE_VERSION}}-alpine AS runner

WORKDIR /app

# Set production environment
ENV NODE_ENV=production
ENV PORT={{PORT}}

# Create non-root user
RUN addgroup --system --gid 1001 nodejs && \
    adduser --system --uid 1001 appuser

# Copy built application
COPY --from=builder --chown=appuser:nodejs /app/package*.json ./
COPY --from=builder --chown=appuser:nodejs /app/node_modules ./node_modules

# Copy build output or source
COPY --from=builder --chown=appuser:nodejs /app/dist* ./dist/
COPY --from=builder --chown=appuser:nodejs /app/build* ./build/
COPY --from=builder --chown=appuser:nodejs /app/src* ./src/

# Switch to non-root user
USER appuser

# Expose port
EXPOSE {{PORT}}

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:{{PORT}}/health || exit 1

# Start application
CMD ["node", "{{ENTRY_POINT}}"]
