FROM node:20-slim AS builder

WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm ci

# Copy the rest of the source code
COPY . .

# Build the application (optimized for production)
RUN npm run build

# Production stage
FROM node:20-slim AS runner

# Install necessary system dependencies
RUN apt-get update && apt-get install -y \
    curl \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Set environment to production
ENV NODE_ENV=production

# Copy package files and install production dependencies
COPY package*.json ./
RUN npm ci --production

# Copy build artifacts from the builder stage
COPY --from=builder /app/dist ./dist

# Copy schema files for Drizzle
COPY ./shared/schema.ts ./shared/
COPY ./drizzle.config.ts ./

# Create a directory for logs
RUN mkdir -p /app/logs

# Set default environment variables (these should be overridden at runtime)
ENV DATABASE_URL=postgres://postgres:postgres@postgres:5432/postgres
ENV REDIS_URL=redis://redis:6379
ENV SESSION_SECRET=changeme

# Set rate limiting configuration
ENV RATE_LIMIT_WINDOW_MS=900000
ENV RATE_LIMIT_MAX_REQUESTS=100

# Set compression level (1-9, where 9 is maximum compression)
ENV COMPRESSION_LEVEL=6

# Set logging level (debug, info, warn, error)
ENV LOG_LEVEL=info

# Expose the port the app runs on
EXPOSE 5000

# Add startup script with health check
COPY ./docker-entrypoint.sh /
RUN chmod +x /docker-entrypoint.sh

# Health check to ensure the application is running properly
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
  CMD curl -f http://localhost:5000/api/health || exit 1

# Start the application using the entrypoint script
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["node", "dist/index.js"]