name: Update AUR

on:
  workflow_run:
    workflows: ["Release"]
    types:
      - completed
  workflow_dispatch:
    inputs:
      version:
        description: "Version to update (e.g., 2.8.1, leave empty for latest release)"
        required: false
        type: string

jobs:
  trigger-aur-update:
    name: Trigger AUR Update
    runs-on: ubuntu-latest
    if: ${{ github.event_name == 'workflow_dispatch' ||
      github.event.workflow_run.conclusion == 'success' }}

    steps:
      - name: Get latest release
        if: github.event_name == 'workflow_dispatch' && inputs.version == ''
        id: latest
        run: |
          LATEST=$(gh api repos/${{ github.repository }}/releases/latest --jq '.tag_name')
          echo "version=$LATEST" >> $GITHUB_OUTPUT
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Get version from workflow_run
        if: github.event_name == 'workflow_run'
        id: workflow_run_version
        run: |
          # Get the release tag that triggered the binary build workflow
          TAG=$(gh api repos/${{ github.repository }}/releases/latest --jq '.tag_name')
          echo "version=$TAG" >> $GITHUB_OUTPUT
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Trigger AUR repository
        run: |
          VERSION="${{ inputs.version || steps.latest.outputs.version || steps.workflow_run_version.outputs.version }}"
          VERSION="${VERSION#v}"  # Remove 'v' prefix if present
          gh api repos/jolars/panache-aur/dispatches \
            -f event_type=new-release \
            -f client_payload[version]="$VERSION"
        env:
          GH_TOKEN: ${{ secrets.RELEASE_TOKEN }}
