FROM node:24-alpine AS base

# Install system dependencies
RUN apk add --no-cache \
    python3 \
    make \
    g++ \
    libc6-compat \
    vips-dev \
    curl

# Install pnpm globally
RUN npm install -g pnpm

# Configure pnpm
RUN pnpm config set store-dir /.pnpm-store
RUN pnpm config set network-timeout 300000
RUN pnpm config set fetch-retries 10
RUN pnpm config set fetch-retry-factor 2

FROM base AS deps

WORKDIR /app

# Copy package files
COPY package.json pnpm-lock.yaml ./

# Install dependencies with retry logic
RUN --mount=type=cache,id=pnpm,target=/.pnpm-store \
    pnpm install --frozen-lockfile || \
    (sleep 5 && pnpm install --frozen-lockfile) || \
    (sleep 10 && pnpm install --frozen-lockfile --no-frozen-lockfile)

FROM base AS build-deps

WORKDIR /app

# Copy package files
COPY package.json pnpm-lock.yaml ./

# Install all dependencies including dev dependencies
RUN --mount=type=cache,id=pnpm,target=/.pnpm-store \
    pnpm install --frozen-lockfile || \
    (sleep 5 && pnpm install --frozen-lockfile) || \
    (sleep 10 && pnpm install --frozen-lockfile --no-frozen-lockfile)

FROM build-deps AS builder

# Copy source code
COPY . .

# Build the application
RUN pnpm run build

FROM node:20-alpine AS runtime

# Install pnpm for runtime
RUN npm install -g pnpm

WORKDIR /app

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

# Copy production dependencies
COPY --from=deps /app/node_modules ./node_modules

# Copy package.json for any runtime needs
COPY package.json ./

# Set environment variables
ENV HOST=0.0.0.0 \
    PORT=4321 \
    NODE_ENV=production

# Expose port
EXPOSE 4321

# Start the application
CMD ["node", "./dist/server/entry.mjs"]
