name: PR Checks

on:
  pull_request:
    types: [opened, edited, synchronize, reopened]

concurrency:
  group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
  cancel-in-progress: true

jobs:
  branch-naming:
    name: Branch Naming
    runs-on: ubuntu-latest
    timeout-minutes: 2
    steps:
      - name: Validate branch name
        env:
          BRANCH: ${{ github.head_ref }}
        run: |
          REGEX="^(feat|fix|refactor|perf|docs|chore|test|batch)/([0-9]+-)?.*$"
          if [[ ! "$BRANCH" =~ $REGEX ]]; then
            echo "::error::Branch '$BRANCH' does not match required format: <type>/[<id>-]<desc>"
            echo "Example: feat/96-login or fix/123-bug"
            exit 1
          fi
          echo "✓ Branch naming correct: $BRANCH"

  issue-link:
    name: Issue Link
    runs-on: ubuntu-latest
    timeout-minutes: 2
    steps:
      - name: Validate issue link
        env:
          PR_BODY: ${{ github.event.pull_request.body }}
          BRANCH: ${{ github.head_ref }}
        run: |
          # Extract issue ID from branch name (e.g., feat/123-description → 123)
          BRANCH_ISSUE=""
          if [[ "$BRANCH" =~ ^[^/]+/([0-9]+)- ]]; then
            BRANCH_ISSUE="${BASH_REMATCH[1]}"
          fi

          BODY_FILE=$(mktemp)
          printf '%s' "$PR_BODY" > "$BODY_FILE"

          # Check: PR body must contain #<number> in resolve/fix/close/refs pattern
          # Support both single issue (#82) and multiple issues (#82, #78, #77)
          if ! grep -Eqi "\*?(resolves|fixes|closes|refs)\*?\s*:?\s*#([0-9]+)(\s*,\s*#[0-9]+)*" "$BODY_FILE"; then
            echo "::error::PR body must contain an issue link"
            echo ""
            echo "Expected one of:"
            echo "  Resolves #N   (this PR closes/fixes the issue)"
            echo "  Fixes #N      (this PR fixes the issue)"
            echo "  Closes #N     (this PR closes the issue)"
            echo "  Refs #N       (this PR references the issue)"
            echo ""
            if [[ -n "$BRANCH_ISSUE" ]]; then
              echo "Hint: Branch references issue #$BRANCH_ISSUE — did you mean 'Resolves #$BRANCH_ISSUE'?"
            fi
            rm -f "$BODY_FILE"
            exit 1
          fi

          # If branch has issue ID, warn if PR body doesn't reference the same one
          if [[ -n "$BRANCH_ISSUE" ]]; then
            if ! grep -Eqi "#$BRANCH_ISSUE" "$BODY_FILE"; then
              echo "::warning::Branch references #$BRANCH_ISSUE but PR body doesn't — consider adding 'Resolves #$BRANCH_ISSUE'"
            fi
          fi

          rm -f "$BODY_FILE"
          echo "✓ Issue link found in PR body"
