# Multi-stage build for EuchreCamp Next.js application

# Stage 1: Builder
FROM oven/bun:alpine AS builder

# Install dependencies (needed for native modules)
RUN apk add --no-cache python3 make g++ nodejs npm

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies (including dev dependencies for building)
RUN npm ci --legacy-peer-deps

# Copy source code
COPY . .

# Generate Prisma client (with dummy PostgreSQL DATABASE_URL for build-time generation)
# Note: A dummy URL is used since the real database is not available during build
RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" npx prisma generate

# Build the application (with dummy DATABASE_URL for static page generation and git commit)
ARG GIT_COMMIT=unknown
RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" NEXT_PUBLIC_GIT_COMMIT=$GIT_COMMIT bun run build

# Stage 2: Test runner (includes dev dependencies for testing)
FROM oven/bun:alpine AS test-runner

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

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./

# Install ALL dependencies (including dev dependencies for testing)
RUN npm ci --legacy-peer-deps

# Copy source code
COPY . .

# Generate Prisma client
RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" npx prisma generate

# Stage 3: Production runner
FROM oven/bun:alpine AS runner

# Install dumb-init and npm for production install
RUN apk add --no-cache dumb-init nodejs npm

# 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/package-lock.json ./package-lock.json
COPY --from=builder --chown=euchre:euchre /app/prisma ./prisma

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

# Generate Prisma client
# Note: We need to set DATABASE_URL even for generation because prisma.config.ts requires it
RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" npx prisma generate

# 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 ["bun", "run", "start"]
