FROM node:18-alpine

# Set working directory
WORKDIR /app

# Install system dependencies
RUN apk add --no-cache \
    curl \
    bash \
    && rm -rf /var/cache/apk/*

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

# Copy package files
COPY package*.json ./

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

# Copy source code
COPY src/ ./src/

# Copy environment configuration
COPY config.env ./

# Create logs directory
RUN mkdir -p logs && \
    chown -R unison:nodejs logs

# Change ownership of app directory
RUN chown -R unison:nodejs /app

# Switch to non-root user
USER unison

# Expose port
EXPOSE 8010

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
  CMD curl -f http://localhost:8010/health || exit 1

# Set environment variables
ENV NODE_ENV=production
ENV PORT=8010
ENV HOST=0.0.0.0

# Start the application
CMD ["node", "src/app.js"]
