# API, migrations and workers share one image (monorepo build)
FROM node:22-alpine AS build
WORKDIR /app
COPY package.json package-lock.json tsconfig.base.json ./
COPY packages ./packages
COPY apps/api ./apps/api
COPY workers ./workers
COPY scripts ./scripts
RUN npm ci --workspaces --include-workspace-root --ignore-scripts \
      -w @justice-choice/types -w @justice-choice/ranking-engine -w @justice-choice/seo-engine -w @justice-choice/database -w @justice-choice/search -w @justice-choice/api \
      -w @justice-choice/ranking-worker -w @justice-choice/data-import-worker -w @justice-choice/verification-worker -w @justice-choice/sitemap-worker
RUN npm run build:packages && npm run build -w @justice-choice/api \
    && for w in ranking-worker data-import-worker verification-worker sitemap-worker; do npm run build -w @justice-choice/$w; done

FROM node:22-alpine AS development
RUN apk add --no-cache bash postgresql-client procps
ENV NODE_ENV=development
WORKDIR /app
COPY --from=build /app /app
# Local upload storage (development only — production uses S3_BUCKET). Owned by the runtime user.
RUN mkdir -p /app/uploads/sitemaps && chown -R node:node /app/uploads
USER node
EXPOSE 4000
CMD ["node", "apps/api/dist/main.js"]

# Production does not contain executable fictional seed fixtures or test harnesses.
FROM development AS production
USER root
RUN rm -rf packages/database/src/seed packages/database/dist/seed scripts apps/api/test packages/ranking-engine/src/ranking.test.ts packages/seo-engine/src/seo.test.ts \
    && npm prune --omit=dev --ignore-scripts
ENV NODE_ENV=production
USER node
