# Build stage
FROM oven/bun:1-alpine as builder

# Install dependencies for Prisma and Playwright
RUN apk add --no-cache openssl chromium

WORKDIR /app

# Copy workspace files
COPY package.json bun.lockb ./
COPY apps/wcag-ada/worker/package.json ./apps/wcag-ada/worker/
COPY apps/wcag-ada/scanner/package.json ./apps/wcag-ada/scanner/
COPY apps/wcag-ada/config/package.json ./apps/wcag-ada/config/
COPY apps/wcag-ada/shared/package.json ./apps/wcag-ada/shared/
COPY lib/service/core-config/package.json ./lib/service/core-config/
COPY lib/service/core-logger/package.json ./lib/service/core-logger/

# Install dependencies
RUN bun install --frozen-lockfile

# Copy source code
COPY apps/wcag-ada/worker ./apps/wcag-ada/worker
COPY apps/wcag-ada/scanner ./apps/wcag-ada/scanner
COPY apps/wcag-ada/config ./apps/wcag-ada/config
COPY apps/wcag-ada/shared ./apps/wcag-ada/shared
COPY lib/service/core-config ./lib/service/core-config
COPY lib/service/core-logger ./lib/service/core-logger
COPY tsconfig.json ./

# Generate Prisma client
WORKDIR /app/apps/wcag-ada/worker
RUN bunx prisma generate

# Build the application
RUN bun run build

# Production stage
FROM oven/bun:1-alpine

# Install runtime dependencies including Chromium
RUN apk add --no-cache \
    openssl \
    chromium \
    nss \
    freetype \
    freetype-dev \
    harfbuzz \
    ca-certificates \
    ttf-freefont \
    nodejs \
    yarn

# Tell Puppeteer/Playwright to use installed Chromium
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true \
    PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser \
    PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=true \
    PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium-browser

WORKDIR /app

# Copy built application
COPY --from=builder /app/apps/wcag-ada/worker/dist ./dist
COPY --from=builder /app/apps/wcag-ada/worker/node_modules ./node_modules
COPY --from=builder /app/apps/wcag-ada/worker/prisma ./prisma
COPY --from=builder /app/apps/wcag-ada/worker/package.json ./

# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
    adduser -S nodejs -u 1001

# Set ownership
RUN chown -R nodejs:nodejs /app

USER nodejs

# Expose port for health check
EXPOSE 3002

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3002/health || exit 1

# Start the application
CMD ["bun", "run", "start"]