name: PR Title Check for JIRA Ticket

on:
  pull_request:
    types:
      - opened
      - synchronize
    branches:
      - main
      - master

jobs:
  check-pr-title:
    runs-on: ubuntu-latest
    permissions:
      pull-requests: read
    steps:
      - name: Fetch current PR title
        id: pr-title
        run: |
          set -euo pipefail
          
          PR_NUMBER="${{ github.event.pull_request.number }}"
          if [ -z "${PR_NUMBER}" ]; then
            echo "❌ Error: PR number is not available"
            exit 1
          fi
          
          echo "Fetching PR #${PR_NUMBER} details..."
          API_RESPONSE=$(curl -s -w "\n%{http_code}" \
            -H "Authorization: Bearer ${{ github.token }}" \
            -H "Accept: application/vnd.github.v3+json" \
            "https://api.github.com/repos/${{ github.repository }}/pulls/${PR_NUMBER}")
          
          HTTP_CODE=$(echo "$API_RESPONSE" | tail -n1)
          API_BODY=$(echo "$API_RESPONSE" | sed '$d')
          
          if [ "${HTTP_CODE}" != "200" ]; then
            echo "❌ Error: Failed to fetch PR details (HTTP ${HTTP_CODE})"
            echo "Response: ${API_BODY}"
            exit 1
          fi
          
          PR_TITLE=$(echo "$API_BODY" | python3 -c "
          import sys, json
          try:
              data = json.load(sys.stdin)
              title = data.get('title', '')
              if not title:
                  print('ERROR: PR title is empty', file=sys.stderr)
                  sys.exit(1)
              print(title)
          except json.JSONDecodeError as e:
              print(f'ERROR: Invalid JSON response: {e}', file=sys.stderr)
              sys.exit(1)
          except KeyError as e:
              print(f'ERROR: Missing field in response: {e}', file=sys.stderr)
              sys.exit(1)
          except Exception as e:
              print(f'ERROR: Unexpected error: {e}', file=sys.stderr)
              sys.exit(1)
          ")
          
          if [ -z "${PR_TITLE}" ]; then
            echo "❌ Error: PR title is empty"
            exit 1
          fi
          
          echo "title=${PR_TITLE}" >> $GITHUB_OUTPUT
          echo "Current PR title: ${PR_TITLE}"
      - name: Validate PR title contains CAP-xxxx
        run: |
          set -euo pipefail
          
          PR_TITLE="${{ steps.pr-title.outputs.title }}"
          
          if [ -z "${PR_TITLE}" ]; then
            echo "❌ Error: PR title is not available from previous step"
            exit 1
          fi
          
          if ! echo "${PR_TITLE}" | grep -qE 'CAP-[0-9]+'; then
            echo "❌ PR title must contain a JIRA ticket id like CAP-1234"
            echo "Current PR title: ${PR_TITLE}"
            exit 1
          else
            echo "✅ PR title is valid: ${PR_TITLE}"
          fi
