name: Validate GraphQL Schema Updates

on:
  repository_dispatch:
    types: [graphql-schema-updated]
  workflow_dispatch:
    inputs:
      schema_url:
        description: "GraphQL schema URL to validate/update"
        required: true
        type: string

permissions:
  id-token: write
  contents: write
  pull-requests: write

jobs:
  validate-schema:
    if: ${{ !startsWith(github.repository, 'Embrace-AI/template-') }}
    runs-on: codebuild-GithubDev-${{ github.run_id }}-${{ github.run_attempt }}

    steps:
      - uses: actions/checkout@v5

      - name: Setup pnpm
        uses: pnpm/action-setup@v4

      - name: Setup node cache
        uses: actions/setup-node@v5
        with:
          node-version: 22.19.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
        run: pnpm add -g @embrace-ai/infra-api-schema-sync@latest

      - name: Configure aws credentials
        uses: aws-actions/configure-aws-credentials@v5.0.0
        with:
          role-to-assume: ${{ secrets.AWS_DEPLOY_ROLE_DEV }}
          aws-region: ${{ vars.AWS_REGION }}

      - name: Set schema URL and source repo
        id: set-schema-url
        run: |
          SCHEMA_URL="${{ github.event.client_payload.schemaUrl || github.event.inputs.schema_url || '' }}"
          if [ -z "$SCHEMA_URL" ]; then
            echo "❌ schemaUrl not provided via repository_dispatch payload or workflow input"; exit 1
          fi
          echo "schema_url=$SCHEMA_URL" >> "$GITHUB_OUTPUT"

      - name: Display schema update context
        run: |
          echo "Schema update received from: ${{ github.event.client_payload.sourceRepo }}"
          echo "Schema URL: ${{ steps.set-schema-url.outputs.schema_url }}"
          echo "Source commit: ${{ github.event.client_payload.commit }}"
          echo "Source branch: ${{ github.event.client_payload.branch }}"
          echo "Timestamp: ${{ github.event.client_payload.timestamp }}"

      - name: Fetch updated schema
        run: api-tool fetch --url ${{ steps.set-schema-url.outputs.schema_url }} --output new-schema.graphql

      - name: Update local schema files
        id: update-schema
        run: |
          echo "🔍 Searching for local schema files to update..."
          api-tool update-local-schema \
            --schema-url "${{ steps.set-schema-url.outputs.schema_url }}" \
            --schema-file new-schema.graphql \
            --output schema-update-result.json

          # Read the results
          if [ -f schema-update-result.json ]; then
            SERVICE_NAME=$(jq -r '.serviceName // "unknown"' schema-update-result.json)
            UPDATED_COUNT=$(jq -r '.updatedFiles | length' schema-update-result.json)
            HAS_CHANGES=$(jq -r '.hasChanges' schema-update-result.json)

            echo "service_name=$SERVICE_NAME" >> $GITHUB_OUTPUT
            echo "updated_count=$UPDATED_COUNT" >> $GITHUB_OUTPUT
            echo "has_changes=$HAS_CHANGES" >> $GITHUB_OUTPUT

            if [ "$HAS_CHANGES" = "true" ]; then
              echo "✅ Updated $UPDATED_COUNT schema file(s) for service: $SERVICE_NAME"
              jq -r '.updatedFiles[]' schema-update-result.json | while read file; do
                echo "  - $file"
              done
            else
              echo "ℹ️  No changes detected in schema files"
            fi
          else
            echo "has_changes=false" >> $GITHUB_OUTPUT
            echo "⚠️  No schema files found to update"
          fi
      - name: Validate queries against new schema
        id: validate
        run: api-tool validate --schema new-schema.graphql --queries '**/*' --output report.json

      - name: Check for issues
        id: check-issues
        run: |
          if [ -s report.json ] && [ "$(jq '.issues | length' report.json)" -gt 0 ]; then
            echo "has_issues=true" >> $GITHUB_OUTPUT
            echo "issue_count=$(jq '.issues | length' report.json)" >> $GITHUB_OUTPUT
          else
            echo "has_issues=false" >> $GITHUB_OUTPUT
            echo "issue_count=0" >> $GITHUB_OUTPUT
          fi

      - name: Generate validation summary
        id: gen-summary
        run: |
          # Always generate summary, even if no issues (for consistency)
          if [ ! -f report.json ]; then
            echo "[]" > report.json
          fi
          api-tool summarize --report report.json --output GRAPHQL_ISSUES.md

          # Also generate a summary of updated files
          if [ -f schema-update-result.json ]; then
            echo "## 📝 Updated Schema Files" > SCHEMA_CHANGES.md
            echo "" >> SCHEMA_CHANGES.md
            jq -r '.updatedFiles[]' schema-update-result.json | while read file; do
              echo "- \`$file\`" >> SCHEMA_CHANGES.md
            done
            echo "" >> SCHEMA_CHANGES.md
          fi

          # Expose summaries as step outputs for later steps (multiline-safe)
          {
            echo 'issues_summary<<EOF'
            cat GRAPHQL_ISSUES.md
            echo EOF
          } >> $GITHUB_OUTPUT

          {
            echo 'schema_changes<<EOF'
            if [ -f SCHEMA_CHANGES.md ]; then
              cat SCHEMA_CHANGES.md
            else
              echo "- No files updated"
            fi
            echo EOF
          } >> $GITHUB_OUTPUT
      - name: Clean up non-source artifacts before PR
        run: |
          rm -f new-schema.graphql report.json GRAPHQL_ISSUES.md SCHEMA_CHANGES.md schema-update-result.json

      - name: Commit and create PR
        if: steps.update-schema.outputs.has_changes == 'true'
        id: create-pr
        uses: peter-evans/create-pull-request@v6
        with:
          commit-message: "fix: GraphQL Schema Update - ${{ steps.update-schema.outputs.service_name }}${{ github.event_name == 'repository_dispatch' && format(' from {0}', github.event.client_payload.sourceRepo) || '' }}"
          branch: "graphql/schema-update-${{ github.run_id }}"
          title: "fix: GraphQL Schema Update - ${{ steps.update-schema.outputs.service_name }} (${{ steps.check-issues.outputs.issue_count }} issues)"
          body: |
            # GraphQL Schema Update Impact Report

            ## Summary

            **Service:** `${{ steps.update-schema.outputs.service_name }}`
            **Updated Files:** ${{ steps.update-schema.outputs.updated_count }}
            **Validation Issues:** ${{ steps.check-issues.outputs.issue_count }}
            **Status:** ${{ steps.check-issues.outputs.has_issues == 'true' && '⚠️ Action Required' || '✅ Ready to Merge' }}

            ---

            ## Schema Files Updated

            The following schema files have been updated with the latest schema from the source:

            ${{ steps.gen-summary.outputs.schema_changes }}

            ---

            ## ${{ steps.check-issues.outputs.has_issues == 'true' && '⚠️ Validation Issues Found' || '✅ No Validation Issues' }}

            ${{ steps.check-issues.outputs.has_issues == 'true' && 'The following GraphQL queries are incompatible with the updated schema and need to be fixed:\n\n' || 'All existing GraphQL queries are compatible with the updated schema. No changes to queries are required.\n\n' }}${{ steps.gen-summary.outputs.issues_summary }}

            ---

            ## Source Information

            ${{ github.event_name == 'repository_dispatch' && format('- **Schema Source:** {0}', github.event.client_payload.sourceRepo) || '' }}
            - **Schema URL:** ${{ github.event.client_payload.schemaUrl }}
            ${{ github.event_name == 'repository_dispatch' && format('- **Source Commit:** {0}', github.event.client_payload.commit) || '' }}
            ${{ github.event_name == 'repository_dispatch' && format('- **Source Branch:** {0}', github.event.client_payload.branch) || '' }}
            ${{ github.event_name == 'repository_dispatch' && format('- **Update Time:** {0}', github.event.client_payload.timestamp) || '' }}
            - **Trigger:** ${{ github.event_name }}

            ---

            ## 🚀 Next Steps

            ${{ steps.check-issues.outputs.has_issues == 'true' && '1. ⚠️ **Review the validation issues above**\n2. 🔧 **Update the affected GraphQL queries** to match the new schema\n3. **Test your changes**\n4.  **Push your fixes** to this branch\n5. **Merge this PR** once all issues are resolved' || '1. **Review the schema changes** in the Files Changed tab\n2. **Verify the changes** look correct\n3. **Merge this PR** to update your schema' }}

      - name: Display validation results
        if: github.event_name == 'workflow_dispatch'
        run: |
          echo "## GraphQL Schema Validation Results" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "**Schema URL:** ${{ steps.set-schema-url.outputs.schema_url }}" >> $GITHUB_STEP_SUMMARY
          echo "**Event:** ${{ github.event_name }}" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY

          if [ "${{ steps.check-issues.outputs.has_issues }}" = "true" ]; then
            echo "### ❌ Found ${{ steps.check-issues.outputs.issue_count }} issue(s)" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            if [ -f GRAPHQL_ISSUES.md ]; then
              cat GRAPHQL_ISSUES.md >> $GITHUB_STEP_SUMMARY
            fi
          else
            echo "### ✅ No compatibility issues found!" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "The schema is compatible with all existing GraphQL queries." >> $GITHUB_STEP_SUMMARY
          fi

      - name: No changes needed
        if: steps.update-schema.outputs.has_changes == 'false'
        run: |
          echo "✅ Schema is already up to date - no PR needed"
          echo "### ✅ Schema Already Up To Date" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "The fetched schema matches the current schema file(s). No changes or action needed." >> $GITHUB_STEP_SUMMARY
          if [ "${{ steps.check-issues.outputs.has_issues }}" = "false" ]; then
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "All existing queries are compatible with the schema." >> $GITHUB_STEP_SUMMARY
          fi
