# ============= STAGE 1: BUILD =============
FROM node:22.22.0-alpine AS builder

# Install build tools for native modules (sharp, pg, etc.)
RUN apk add --no-cache python3 make g++

# Install Bun
RUN npm install -g bun

WORKDIR /app

# Copy dependency + lock files first (cache layer)
COPY package.json bun.lock ./

# Install all dependencies (including devDependencies for build)
RUN bun install

# Copy source code
COPY . .

# Verify required config files
RUN test -f .env && echo ".env exists" || (echo ".env missing" && exit 1)

# Generate Prisma client
RUN bun x prisma generate

# Build Nuxt app (memory limit is set in package.json build script)
RUN bun run build

# ============= STAGE 2: PRODUCTION =============
FROM node:22.22.0-alpine AS runner

WORKDIR /app

# Copy built output and .env for runtime env vars
COPY --from=builder /app/.output .output
COPY --from=builder /app/.env .env

EXPOSE 3000

# Node 22 --env-file loads .env safely without shell expansion issues
CMD ["node", "--env-file=.env", ".output/server/index.mjs"]
