# This is a multi-service Dockerfile that builds all services
# Use with --target flag to build specific services

# Base stage for all services
FROM oven/bun:1-alpine as base
RUN apk add --no-cache openssl
WORKDIR /app

# Dependencies stage
FROM base as deps
COPY package.json bun.lockb ./
COPY apps/wcag-ada/*/package.json ./apps/wcag-ada/
COPY lib/service/core-config/package.json ./lib/service/core-config/
COPY lib/service/core-logger/package.json ./lib/service/core-logger/
RUN bun install --frozen-lockfile

# Builder stage
FROM base as builder
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/package.json ./package.json
COPY . .
WORKDIR /app/apps/wcag-ada

# Generate Prisma clients
RUN cd api && bunx prisma generate
RUN cd worker && bunx prisma generate

# Build all services
RUN bun run build

# API Runtime
FROM base as api
COPY --from=builder /app/apps/wcag-ada/api/dist ./dist
COPY --from=builder /app/apps/wcag-ada/api/node_modules ./node_modules
COPY --from=builder /app/apps/wcag-ada/api/prisma ./prisma
COPY --from=builder /app/apps/wcag-ada/api/package.json ./

RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001
RUN chown -R nodejs:nodejs /app
USER nodejs

EXPOSE 3001
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3001/health || exit 1
CMD ["bun", "run", "start"]

# Worker Runtime
FROM base as worker
RUN apk add --no-cache chromium nss freetype harfbuzz ca-certificates ttf-freefont

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

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 ./

RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001
RUN chown -R nodejs:nodejs /app
USER nodejs

EXPOSE 3002
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3002/health || exit 1
CMD ["bun", "run", "start"]

# Dashboard Runtime
FROM nginx:alpine as dashboard
RUN apk add --no-cache curl

COPY apps/wcag-ada/dashboard/nginx.conf /etc/nginx/nginx.conf
COPY --from=builder /app/apps/wcag-ada/dashboard/dist /usr/share/nginx/html

RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001
RUN chown -R nodejs:nodejs /usr/share/nginx/html /var/cache/nginx /var/log/nginx /etc/nginx/conf.d
RUN touch /var/run/nginx.pid && chown -R nodejs:nodejs /var/run/nginx.pid
USER nodejs

EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:8080/ || exit 1
CMD ["nginx", "-g", "daemon off;"]