# Build stage
FROM node:20-alpine AS builder

# Add build tools for native canvas compilation (fixes 16k page size issues on RPi5 ARM64)
RUN apk add --no-cache python3 make g++ cairo-dev pango-dev jpeg-dev giflib-dev librsvg-dev

WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm ci

# Copy source code
COPY . .

# Generate Prisma client
RUN npx prisma generate

# Build the application
RUN npm run build

# Production stage
FROM node:20-alpine AS production

# Add runtime dependencies for canvas & prisma
RUN apk add --no-cache cairo pango jpeg giflib librsvg openssl
WORKDIR /app

# Copy package files
COPY package*.json ./

# Install production dependencies only (with build tools for canvas)
RUN apk add --no-cache --virtual .build-deps python3 make g++ cairo-dev pango-dev jpeg-dev giflib-dev librsvg-dev \
    && npm ci --omit=dev --build-from-source=canvas \
    && apk del .build-deps

# Copy Prisma schema and generate client
COPY prisma ./prisma
RUN npx prisma generate

# Copy built application
COPY --from=builder /app/dist ./dist

# Copy i18n files
COPY --from=builder /app/src/i18n ./dist/i18n

# Copy league filter config files (critical: without these, feeder stores ALL matches)
COPY top_leagues.json basketball_top_leagues.json ./

# Set environment
ENV NODE_ENV=production

# Expose port
EXPOSE 3000

# Start the application
CMD ["node", "dist/main.js"]
