# Multi-stage Dockerfile for Zeiterfassung Application
# Optimized for production deployment

# ============================================
# Stage 1: Build - Install dependencies
# ============================================
FROM node:18-alpine AS builder

# Add metadata
LABEL maintainer="timetracker"
LABEL description="Time tracking application with persistent timer and German break rules"

WORKDIR /app

# Copy package files for dependency installation
COPY package*.json ./

# Install only production dependencies
# Using npm ci for reproducible builds
RUN npm ci --only=production && \
    npm cache clean --force

# ============================================
# Stage 2: Runtime - Slim production image
# ============================================
FROM node:18-alpine

WORKDIR /app

# Install dumb-init for proper signal handling
RUN apk add --no-cache dumb-init

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

# Copy dependencies from builder stage
COPY --from=builder /app/node_modules ./node_modules

# Copy application files
COPY --chown=nodejs:nodejs server.js ./
COPY --chown=nodejs:nodejs package*.json ./
COPY --chown=nodejs:nodejs db ./db
COPY --chown=nodejs:nodejs public ./public

# Create data directory for SQLite database with proper permissions
RUN mkdir -p /app/db && \
    chown -R nodejs:nodejs /app/db

# Switch to non-root user
USER nodejs

# Expose the application port
EXPOSE 3000

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD node -e "require('http').get('http://localhost:3000/', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"

# Set environment variables
ENV NODE_ENV=production \
    PORT=3000

# Use dumb-init to handle signals properly
ENTRYPOINT ["dumb-init", "--"]

# Run the application
CMD ["node", "server.js"]
