# ==============================================================================
# Base stage - Common dependencies and setup
# ==============================================================================
FROM node:18-alpine AS base

# Build argument for NODE_ENV
ARG NODE_ENV=production

# Install security updates
RUN apk --no-cache upgrade

# Create app directory and set up non-root user
WORKDIR /app
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nodejs -u 1001

# Copy package files
COPY package*.json ./

# ==============================================================================
# Dependencies stage - Install all dependencies
# ==============================================================================
FROM base AS deps

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

# ==============================================================================
# Build stage - Compile TypeScript
# ==============================================================================
FROM deps AS build

# Copy source code
COPY . .

# Build the application
RUN npm run build

# ==============================================================================
# Production dependencies stage - Install only production dependencies
# ==============================================================================
FROM base AS prod-deps

# Install only production dependencies
RUN npm ci --only=production && npm cache clean --force

# ==============================================================================
# Staging stage - For staging environment
# ==============================================================================
FROM base AS staging

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

# Copy built application
COPY --from=build /app/dist ./dist
COPY --from=build /app/package*.json ./

# Copy environment files
COPY --from=build /app/.env* ./

# Change ownership to nodejs user
RUN chown -R nodejs:nodejs /app

# Switch to non-root user
USER nodejs

# Expose port
EXPOSE 8080

# Set staging environment
ENV NODE_ENV=staging

# Start the application
CMD ["npm", "start"]

# ==============================================================================
# Production stage - For production environment (default)
# ==============================================================================
FROM base AS production

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

# Copy built application
COPY --from=build /app/dist ./dist
COPY --from=build /app/package*.json ./

# Copy environment files
COPY --from=build /app/.env* ./

# Change ownership to nodejs user
RUN chown -R nodejs:nodejs /app

# Switch to non-root user
USER nodejs

# Expose port
EXPOSE 8080

# Set production environment
ENV NODE_ENV=production

# Start the application
CMD ["npm", "start"] 