name: OpenAPI Report

on:
  workflow_run:
    workflows:
    - OpenAPI Check
    types:
    - completed

jobs:
  metadata:
    name: Generate Metadata
    runs-on: ubuntu-latest
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    outputs:
      pr_number: ${{ steps.pr_number.outputs.pr_number }}
    steps:
    - name: Get Pull Request Number
      id: pr_number
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
      run: |
        API_RESPONSE=$(gh pr list --repo "${GITHUB_REPOSITORY}" --search "${HEAD_SHA}" --state open --json number)
        PR_NUMBER=$(echo "${API_RESPONSE}" | jq '.[0].number')

        echo "repository: ${GITHUB_REPOSITORY}"
        echo "sha: ${HEAD_SHA}"
        echo "response: ${API_RESPONSE}"
        echo "pr: ${PR_NUMBER}"

        echo "pr_number=${PR_NUMBER}" >> "${GITHUB_OUTPUT}"

  comment:
    name: Pull Request Comment
    runs-on: ubuntu-latest
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    needs:
    - metadata
    permissions:
      pull-requests: write
      actions: read
      contents: read
    steps:
    - name: Download OpenAPI Report
      id: download_report
      uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
      with:
        name: openapi-report
        path: openapi-report
        run-id: ${{ github.event.workflow_run.id }}
        github-token: ${{ secrets.GITHUB_TOKEN }}
    - name: Push Comment
      uses: thollander/actions-comment-pull-request@24bffb9b452ba05a4f3f77933840a6a841d1b32b # v3.0.1
      with:
        github-token: ${{ secrets.JF_BOT_TOKEN }}
        file-path: ${{ steps.download_report.outputs.download-path }}/openapi-report.md
        pr-number: ${{ needs.metadata.outputs.pr_number }}
        comment-tag: openapi-report
