name: Create release PR

run-name: Create release PR for new ${{ github.event.inputs.version }} version

on:
  workflow_dispatch:
    inputs:
      version:
        required: true
        type: choice
        description: "What type of release is this"
        options:
          - "major"
          - "minor"
          - "patch"
      update-language-server: 
        required: true
        description: "Update the language server to the latest version?"
        type: boolean


jobs:
  create-release-pr:
    name: Create release PR

    runs-on: ubuntu-latest

    permissions:
      contents: write
      pull-requests: write

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: "16"

      - name: Bump version and push
        run: |
          git config --global user.email "github-actions@github.com"
          git config --global user.name "GitHub Actions"

          NEW_VERSION=$(./script/workflows/increment-version.sh ${{ inputs.version }})

          git checkout -b release/$NEW_VERSION

          npm version $NEW_VERSION --no-git-tag-version
          git add package.json package-lock.json
          git commit -m "Release extension version $NEW_VERSION"

          git push --set-upstream origin release/$NEW_VERSION

          echo "new_version=$NEW_VERSION" >> $GITHUB_ENV
      
      - name: Update language server
        if: ${{ inputs.update-language-server }}
        run: |
          npm install @actions/languageserver@latest @actions/workflow-parser@latest --workspaces=false
          git checkout -- package.json
          npm i

      - uses: stefanzweifel/git-auto-commit-action@3ea6ae190baf489ba007f7c92608f33ce20ef04a
        with: 
          branch: release/${{ env.new_version }}
        if: ${{ inputs.update-language-server }}

      - name: Create PR
        run: |
          LAST_PR=$(gh pr list --repo ${{ github.repository }} --limit 1 --state merged --search "Release version" --json number | jq -r '.[0].number')
          ./script/workflows/generate-release-notes.sh $LAST_PR ${{ env.new_version }}
          gh pr create \
            --title "Release version ${{ env.new_version }}" \
            --body-file releasenotes.md \
            --base main \
            --head release/${{ env.new_version }}
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
