name: Notify Downstream

on:
  push:
    branches: [main]

jobs:
  wait-for-ci:
    runs-on: ubuntu-latest
    steps:
      - name: Wait for CI
        uses: lewagon/wait-on-check-action@v1.5.0
        with:
          ref: ${{ github.sha }}
          check-name: 'Test (ubuntu-latest)'
          repo-token: ${{ secrets.GITHUB_TOKEN }}
          wait-interval: 10

  notify:
    needs: wait-for-ci
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        downstream:
          - meta_cli
          - meta_git_cli
          - meta_project_cli
          - meta_rust_cli
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Extract commit info
        id: commit
        env:
          GH_REPOSITORY: ${{ github.repository }}
          GH_REPO_NAME: ${{ github.event.repository.name }}
          GH_ACTOR: ${{ github.actor }}
        run: |
          write_output() {
            local key="$1" value="$2"
            local delim="__EOF__$(date +%s%N)_$RANDOM"
            {
              printf '%s<<%s\n' "$key" "$delim"
              printf '%s\n' "$value"
              printf '%s\n' "$delim"
            } >> "$GITHUB_OUTPUT"
          }

          MSG=$(git log -1 --pretty=%s)
          write_output message "$MSG"
          write_output repo "$GH_REPOSITORY"
          write_output repo_name "$GH_REPO_NAME"
          write_output actor "$GH_ACTOR"
          write_output sha "$(git rev-parse HEAD)"
          write_output short_sha "$(git rev-parse --short HEAD)"

          re_feat='^feat[!:(]'; re_fix='^fix[!:(]'; re_chore='^chore[!:(]'
          re_docs='^docs[!:(]'; re_test='^test[!:(]'; re_refactor='^refactor[!:(]'
          if [[ "$MSG" =~ $re_feat ]]; then write_output type "feat"
          elif [[ "$MSG" =~ $re_fix ]]; then write_output type "fix"
          elif [[ "$MSG" =~ $re_chore ]]; then write_output type "chore"
          elif [[ "$MSG" =~ $re_docs ]]; then write_output type "docs"
          elif [[ "$MSG" =~ $re_test ]]; then write_output type "test"
          elif [[ "$MSG" =~ $re_refactor ]]; then write_output type "refactor"
          else write_output type "other"
          fi

      - name: Notify ${{ matrix.downstream }}
        uses: peter-evans/repository-dispatch@v4
        with:
          token: ${{ secrets.PARENT_REPO_PAT }}
          repository: gitkb/${{ matrix.downstream }}
          event-type: dependency-updated
          client-payload: >-
            {
              "repo": ${{ toJSON(steps.commit.outputs.repo) }},
              "repo_name": ${{ toJSON(steps.commit.outputs.repo_name) }},
              "sha": ${{ toJSON(steps.commit.outputs.sha) }},
              "short_sha": ${{ toJSON(steps.commit.outputs.short_sha) }},
              "message": ${{ toJSON(steps.commit.outputs.message) }},
              "type": ${{ toJSON(steps.commit.outputs.type) }},
              "actor": ${{ toJSON(steps.commit.outputs.actor) }}
            }
