name: PAT Health Check

on:
  schedule:
    - cron: '0 9 * * 1'  # Every Monday at 9am UTC
  workflow_dispatch:

permissions:
  contents: read
  issues: write

jobs:
  check-pat:
    runs-on: ubuntu-latest
    steps:
      - name: Check COMMUNITY_PAT validity
        env:
          COMMUNITY_PAT: ${{ secrets.COMMUNITY_PAT }}
        run: |
          if [ -z "$COMMUNITY_PAT" ]; then
            echo "::error::COMMUNITY_PAT secret is not set"
            echo "pat_valid=false" >> "$GITHUB_ENV"
            exit 0
          fi

          status=$(curl -s -o /dev/null -w "%{http_code}" \
            -H "Authorization: token $COMMUNITY_PAT" \
            -H "Accept: application/vnd.github+json" \
            https://api.github.com/user)

          if [ "$status" -eq 200 ]; then
            echo "COMMUNITY_PAT is valid (HTTP $status)"
            echo "pat_valid=true" >> "$GITHUB_ENV"
          else
            echo "::error::COMMUNITY_PAT returned HTTP $status"
            echo "pat_valid=false" >> "$GITHUB_ENV"
          fi

      - name: Create issue if PAT is invalid
        if: env.pat_valid == 'false'
        uses: actions/github-script@v7
        with:
          script: |
            const title = 'COMMUNITY_PAT is invalid or missing';
            const body = [
              '## PAT Health Check Failed',
              '',
              'The weekly PAT health check detected that `COMMUNITY_PAT` is either missing or returning an error from the GitHub API.',
              '',
              '**Action required:** Rotate or re-create the PAT and update the repository secret.',
              '',
              `Run: ${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`,
            ].join('\n');

            // Avoid duplicate issues
            const existing = await github.rest.issues.listForRepo({
              owner: context.repo.owner,
              repo: context.repo.repo,
              state: 'open',
              labels: 'pat-health',
              per_page: 1,
            });

            if (existing.data.length > 0) {
              console.log('Open PAT health issue already exists, skipping creation.');
              return;
            }

            await github.rest.issues.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title,
              body,
              labels: ['pat-health'],
            });
