# .github/workflows/emit-schema-update.yml
name: Emit GraphQL Schema Update Event

on:
  push:
    branches:
      - main
    paths:
      - "**/*schema.ts"
  workflow_dispatch: {}

env:
  # Configure these environment variables for your setup
  # SCHEMA_URL will be dynamically generated based on repository and stage
  # You can override this by setting a static URL if needed
  # SCHEMA_URL: "https://api.dev.embrace.ai/v2/graphql/schema"

  # Deployment stage - determines the environment URL pattern
  DEPLOYMENT_STAGE: "dev" # Options: dev, prod, pr-* (e.g., pr-123)
  # Optional: Override service name (auto-detected from repository name if not set)
  # SERVICE_NAME: "your-service-name"

  # Optional: Filter repositories by name pattern (regex)
  REPO_FILTER: ".*" # Default: all repos. Example: "^(frontend|mobile|web)-.*" for specific patterns
permissions:
  id-token: write
  contents: read

jobs:
  emit-schema-update:
    runs-on: ubuntu-latest
    container:
      image: node:22.16.0@sha256:71bcbb3b215b3fa84b5b167585675072f4c270855e37a599803f1a58141a0716
      options: --privileged --user root
    steps:
      - uses: actions/checkout@v4

      - name: Setup pnpm
        uses: pnpm/action-setup@v4
      - name: Setup node cache
        uses: actions/setup-node@v4
        with:
          node-version: 22.16.0
          cache: "pnpm"
      - name: Setup NPM
        env:
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: pnpm config set //registry.npmjs.org/:_authToken "${NPM_TOKEN}"

      - name: Install GraphQL schema sync tool
        # Update below to use the version you want
        run: pnpm install -w @embrace-ai/infra-api-schema-sync@latest

      # Generate dynamic schema URL based on repository and stage
      - name: Generate schema URL
        id: schema-url
        if: ${{ env.SCHEMA_URL == '' || env.SCHEMA_URL == null }}
        run: |
          # Generate URL using the CLI tool
          if [ -n "$SERVICE_NAME" ]; then
            SCHEMA_URL=$(pnpm exec api-tool generate-schema-url --stage "$DEPLOYMENT_STAGE" --service "$SERVICE_NAME")
          else
            SCHEMA_URL=$(pnpm exec api-tool generate-schema-url --stage "$DEPLOYMENT_STAGE")
          fi

          # Set as output for use in later steps
          echo "url=$SCHEMA_URL" >> $GITHUB_OUTPUT
          echo "🌐 Generated schema URL: $SCHEMA_URL"

      # Fetch all organization repositories and dispatch to each
      - name: Dispatch schema update events to all org repositories
        env:
          SCHEMA_URL: ${{ env.SCHEMA_URL || steps.schema-url.outputs.url }}
        run: |
          pnpm exec api-tool dispatch-update \
            --schema-url "$SCHEMA_URL" \
            --token "${{ secrets.GITHUB_TOKEN }}" \
            --source-repo "${{ github.repository }}" \
            --commit "${{ github.sha }}" \
            --branch "${{ github.ref_name }}" \
            --org-name "${{ github.repository_owner }}" \
            --repo-filter "$REPO_FILTER"
