# Multi-stage build for production optimization
FROM node:20-alpine AS base

# Install Playwright dependencies
RUN apk add --no-cache \
    chromium \
    nss \
    freetype \
    freetype-dev \
    harfbuzz \
    ca-certificates \
    ttf-freefont

# Tell Playwright to use the installed chromium
ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium-browser

# Development stage
FROM base AS dev
WORKDIR /app

# Copy package files
COPY package*.json ./
COPY apps/worker/package*.json ./apps/worker/
COPY packages/database/package*.json ./packages/database/
COPY packages/shared/package*.json ./packages/shared/

# Install all dependencies
RUN npm ci

# Copy source code
COPY apps/worker ./apps/worker
COPY packages/database ./packages/database
COPY packages/shared ./packages/shared

WORKDIR /app/apps/worker

CMD ["npm", "run", "dev"]

# Production stage
FROM base AS production
WORKDIR /app

# Copy package files and install dependencies
COPY package*.json ./
COPY apps/worker ./apps/worker
COPY packages/database ./packages/database
COPY packages/shared ./packages/shared

# Install dependencies and build
RUN npm ci --only=production
WORKDIR /app/apps/worker
RUN npm run build

# Create non-root user
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nodejs

USER nodejs

CMD ["npm", "start"]
