# Pamsika WhatsApp Bot - Production Dockerfile
# Multi-stage build for optimized production image

# Stage 1: Build stage
FROM node:18-alpine AS builder

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies (including devDependencies for building)
RUN npm ci --only=production && npm cache clean --force

# Stage 2: Production stage
FROM node:18-alpine AS production

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

# Create app directory and user for security
RUN addgroup -g 1001 -S nodejs && \
    adduser -S pamsika -u 1001

WORKDIR /app

# Copy built dependencies from builder stage
COPY --from=builder --chown=pamsika:nodejs /app/node_modules ./node_modules

# Copy application source code
COPY --chown=pamsika:nodejs . .

# Create necessary directories
RUN mkdir -p logs sessions users && \
    chown -R pamsika:nodejs logs sessions users

# Remove unnecessary files to reduce image size
RUN rm -rf \
    tests/ \
    .git/ \
    .github/ \
    *.md \
    .gitignore \
    .env.example \
    Dockerfile \
    docker-compose.yml \
    package-lock.json

# Set environment variables
ENV NODE_ENV=production \
    PORT=3003 \
    LOG_LEVEL=info \
    WHATSAPP_SESSION_TIMEOUT=3600000 \
    WHATSAPP_MAX_RETRIES=3

# Expose port
EXPOSE 3003

# Switch to non-root user
USER pamsika

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD node -e "const http = require('http'); \
    const options = { hostname: 'localhost', port: 3003, path: '/health', timeout: 5000 }; \
    const req = http.request(options, (res) => { \
        if (res.statusCode === 200) process.exit(0); \
        else process.exit(1); \
    }); \
    req.on('error', () => process.exit(1)); \
    req.on('timeout', () => process.exit(1)); \
    req.end();"

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

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

# Build arguments for metadata
ARG BUILD_DATE
ARG VCS_REF
ARG VERSION

# Add metadata labels
LABEL org.opencontainers.image.title="Pamsika WhatsApp Bot" \
      org.opencontainers.image.description="WhatsApp Ticketing Chatbot for PamsikaOnline" \
      org.opencontainers.image.version=${VERSION} \
      org.opencontainers.image.created=${BUILD_DATE} \
      org.opencontainers.image.revision=${VCS_REF} \
      org.opencontainers.image.vendor="PamsikaOnline" \
      org.opencontainers.image.url="https://pamsikaonline.com" \
      org.opencontainers.image.source="https://github.com/pamsikaonline/whatsapp-bot" \
      org.opencontainers.image.licenses="ISC"
