# ====================== BUILD STAGE ======================
FROM node:20-alpine AS builder

WORKDIR /app

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

# Install production dependencies only
RUN npm ci --only=production

# Copy only the application code (NO config folder)
COPY index.js ./

# ====================== PRODUCTION STAGE ======================
FROM node:20-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 built artifacts from builder stage
COPY --from=builder --chown=nodejs:nodejs /app/package*.json ./
COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=nodejs:nodejs /app/index.js ./

# Create logs directory (will be mounted)
RUN mkdir -p /app/logs && chown nodejs:nodejs /app/logs

# Default environment
ENV NODE_ENV=production
ENV PORT=1977

# Switch to non-root user
USER nodejs

# Expose port
EXPOSE 1977

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=15s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:1977/status || exit 1

# Start the bot
CMD ["node", "index.js"]