# Deploy-time access-control schema-apply job.
#
# One-shot container that applies the merged SpiceDB access schema for all apps
# in this monorepo (`access:merge` + `apply`). It does NOT seed grants —
# group-membership sync and customer-admin grants are owned by the Portal (see
# the centralize-portal-authz RFC). Mirrors the generated app Dockerfile shape
# (base -> builder -> production); the build context is the monorepo root and
# NPM_TOKEN is a build secret.

# Base image with PNPM:
ARG NODE_VERSION=24.16.0
FROM node:${NODE_VERSION}-slim AS base
WORKDIR /repo
ARG PNPM_VERSION=10.6.4
RUN npm install -g pnpm@${PNPM_VERSION}

# Build stage:
FROM base AS builder
ENV CI=true

COPY .npmrc pnpm-lock.yaml pnpm-workspace.yaml ./
RUN --mount=type=secret,id=NPM_TOKEN \
    NPM_TOKEN=$(cat /run/secrets/NPM_TOKEN 2>/dev/null || true) \
    pnpm fetch

COPY . .
RUN --mount=type=secret,id=NPM_TOKEN \
    NPM_TOKEN=$(cat /run/secrets/NPM_TOKEN 2>/dev/null || true) \
    pnpm install --frozen-lockfile --offline

# Bake the merged schema artifact (access/merged.zed +
# access/applications.generated.json) so the schema is deterministic at deploy
# time. The job re-runs `access:merge` at runtime too (via `access:apply`),
# but baking it keeps the image self-describing and lets the build fail fast on
# a broken merge. Skipped when no app has BOTH an access.manifest.ts and a
# schema.zed — that's how the CLI discovers apps, and `access:merge` errors
# ("No app access manifests found") when there are none (e.g. a bare monorepo).
RUN for d in packages/*/src/access; do \
      if [ -f "$d/access.manifest.ts" ] && [ -f "$d/schema.zed" ]; then \
        pnpm run access:merge; \
        break; \
      fi; \
    done

# Production stage - create the final image:
# We keep the full monorepo + node_modules so the @percepta/access-control CLI
# and the app schema sources (for `access:merge`) are available at runtime.
FROM base AS production
WORKDIR /repo

ENV NODE_ENV=production

# Copy the installed monorepo (deps + sources + generated schema artifacts):
COPY --from=builder /repo /repo

# Run as non-root (the node base image's uid 1000); `access:apply` rewrites
# access/merged.zed at runtime, so /repo must be writable by that user.
RUN chown -R 1000:1000 /repo
USER 1000

# Apply the merged schema once and exit (no-op until an app has both an
# access.manifest.ts and a schema.zed). SPICEDB_* env vars are supplied by the
# Ryvn ServiceInstallation.
CMD ["sh", "-c", "for d in packages/*/src/access; do if [ -f \"$d/access.manifest.ts\" ] && [ -f \"$d/schema.zed\" ]; then exec pnpm run access:apply; fi; done; echo 'No app access schemas; nothing to apply.'"]
