# Multi-stage build for EuchreCamp Next.js application

# Stage 1: Builder
FROM node:20-alpine AS builder

# Install dependencies
RUN apk add --no-cache python3 make g++

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies (including dev dependencies for building)
RUN npm ci

# Copy source code
COPY . .

# Build the application
RUN npm run build

# Stage 2: Runner
FROM node:20-alpine AS runner

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

# Create non-root user
RUN addgroup --system --gid 1001 euchre && \
    adduser --system --uid 1001 --ingroup euchre euchre

# Set working directory
WORKDIR /app

# Copy built application from builder
COPY --from=builder --chown=euchre:euchre /app/.next ./.next
COPY --from=builder --chown=euchre:euchre /app/public ./public
COPY --from=builder --chown=euchre:euchre /app/package.json ./package.json
COPY --from=builder --chown=euchre:euchre /app/prisma ./prisma

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

# Switch to non-root user
USER euchre

# Expose port
EXPOSE 3000

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:3000/api/health || exit 1

# Start command
ENTRYPOINT ["dumb-init", "--"]
CMD ["npm", "start"]
