# syntax=docker/dockerfile:1

# =============================================
# Stage 1: Builder (install deps + prepare app)
# =============================================
FROM node:22-alpine AS builder

WORKDIR /app

# Copy package files first for better layer caching
COPY package*.json ./

# Install all dependencies (including dev if needed)
RUN npm ci --ignore-scripts

# Copy source code
COPY . .

# Optional: If you ever add a build step (e.g. TypeScript), run it here
# RUN npm run build

# =============================================
# Stage 2: Production (lean runtime image)
# =============================================
FROM node:22-alpine AS production

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

WORKDIR /app

# Copy package files
COPY package*.json ./

# Install ONLY production dependencies
RUN npm ci --only=production --ignore-scripts && \
    npm cache clean --force

# Copy built/ready files from builder stage
COPY --from=builder /app/src ./src
COPY --from=builder /app/node_modules ./node_modules

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

# Switch to non-root user
USER nodejs

# Expose the port your app listens on (from your config)
EXPOSE 1866

# Detailed healthcheck using the new /health endpoint
HEALTHCHECK --interval=30s --timeout=10s --start-period=20s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:1866/health || exit 1

# Start the app directly with node (better than npm start in containers)
CMD ["node", "src/app.js"]