name: handle-add-device-issue

on:
  issues:
    types: [labeled]

jobs:
  handle-add-device:
    if: github.event.label.name == 'add-device'
    runs-on: ubuntu-latest
    env:
      ISSUE_CONTENT: ${{ github.event.issue.body }}
    steps:
      - uses: actions/checkout@v4
      - name: Parse issue body
        id: handle-add-device
        run: |
          python3 scripts/add_device_handler.py website/docs/repos.json || true
      - name: Commit
        if: steps.handle-add-device.outputs.success == 'true'
        run: |
          git config --local user.name "GitHub Actions"
          git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git add website/docs/repos.json
          git commit -m "add device: ${{ steps.handle-add-device.outputs.device }}"
      - name: Make pull request
        if: steps.handle-add-device.outputs.success == 'true'
        id: cpr
        uses: peter-evans/create-pull-request@v6
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          commit-message: "[add device]: ${{ steps.handle-add-device.outputs.device }}"
          title: "[add device]: ${{ steps.handle-add-device.outputs.device }}"
          body: |
            ${{ steps.handle-add-device.outputs.device }} has been added to the website.
            Related issue: ${{ github.event.issue.html_url }}
          branch: "add-device-${{ github.event.issue.number }}"
          labels: add-device
          delete-branch: true
      - name: Check outputs
        if: ${{ steps.cpr.outputs.pull-request-number }}
        run: |
          echo "Pull Request Number - ${{ steps.cpr.outputs.pull-request-number }}"
          echo "Pull Request URL - ${{ steps.cpr.outputs.pull-request-url }}"
      - uses: Kernel-SU/actions-comment-on-issue@master
        if: ${{ steps.cpr.outputs.pull-request-number }}
        with:
          message: "Automatically created pull request: ${{ steps.cpr.outputs.pull-request-url }}"
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      - uses: Kernel-SU/actions-comment-on-issue@master
        if: steps.handle-add-device.outputs.success != 'true'
        with:
          message: "Cannot create pull request. Please check the issue content. Or you can create a pull request manually."
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      - name: close issue
        uses: peter-evans/close-issue@v3
        with:
          issue-number: ${{ github.event.issue.number }}
          token: ${{ secrets.GITHUB_TOKEN }}
