name: 'Priority Updater'

on:
  issues:
    types: [opened]
  pull_request_target:
    types: [opened]

jobs:
  set_statuses:
    runs-on: ubuntu-latest
    if: ${{ !contains(github.event.issue.labels.*.name, 'manual') && !contains(github.event.pull_request.labels.*.name, 'manual') }}
    steps:
      - name: Get project data
        env:
          GH_TOKEN: ${{ secrets.TEST_TOKEN }}
        run: |
          echo "PROJECT_ID=$(gh project view 27 --owner tauri-apps --format json --jq '.id')" >> $GITHUB_ENV
          gh project field-list 27 --owner tauri-apps --format json > project_data.json
          echo 'PRIORITY_FIELD_ID='$(jq '.fields[] | select(.name== "Priority") | .id' project_data.json) >> $GITHUB_ENV
          echo 'LOW_PRIORITY_ID='$(jq '.fields[] | select(.name== "Priority") | .options[] | select(.name=="Low") | .id' project_data.json) >> $GITHUB_ENV
          echo 'MEDIUM_PRIORITY_ID='$(jq '.fields[] | select(.name== "Priority") | .options[] | select(.name=="Medium") | .id' project_data.json) >> $GITHUB_ENV
          echo 'HIGH_PRIORITY_ID='$(jq '.fields[] | select(.name== "Priority") | .options[] | select(.name=="High") | .id' project_data.json) >> $GITHUB_ENV
          echo 'CRITICAL_PRIORITY_ID='$(jq '.fields[] | select(.name== "Priority") | .options[] | select(.name=="Critical") | .id' project_data.json) >> $GITHUB_ENV

      - name: Default priority
        run: |
          echo 'PRIORITY_ID='${{ env.LOW_PRIORITY_ID }} >> $GITHUB_ENV

      - name: Add project item / Get item id
        env:
          GH_TOKEN: ${{ secrets.TEST_TOKEN }}
        run: |
          echo "ITEM_ID=$(gh project item-add 27 --owner tauri-apps --url https://github.com/tauri-apps/tauri-docs/issues/${{ github.event.pull_request.number || github.event.issue.number }} --format json --jq '.id')" >> $GITHUB_ENV

      - name: Set fields
        if: ${{ github.event.issue.status == 'open' || github.event.pull_request.status == 'open' }}
        env:
          GH_TOKEN: ${{ secrets.TEST_TOKEN }}
        run: |
          gh project item-edit --id ${{ env.ITEM_ID }} --project-id ${{ env.PROJECT_ID }} --field-id ${{ env.PRIORITY_FIELD_ID }} --single-select-option-id ${{ env.PRIORITY_ID }}
