on:
  pull_request:
    types: [closed]
    branches:
      - main
name: Release tag update --force

jobs:
  deploy:
    name: Build Patch from main
    runs-on: ubuntu-latest
    if: ${{ (github.event_name == 'pull_request' && github.event.pull_request.merged == true) || github.event.inputs.services == 'true' }}
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Get latest release tag using GitHub API
        id: get-latest-tag
        run: |
          LATEST_TAG=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
            "https://api.github.com/repos/${{ github.repository }}/releases/latest" \
            | jq -r .tag_name)
          
          # Fallback to git command if API doesn't return a tag
          if [ "$LATEST_TAG" == "null" ] || [ -z "$LATEST_TAG" ]; then
            echo "Not found latest tag"
            exit 100
          fi
          
          echo "LATEST_TAG=$LATEST_TAG" >> $GITHUB_ENV
          echo "Latest tag: $LATEST_TAG"

      - name: Set Remote with GITHUB_TOKEN
        run: |
          git config --unset http.https://github.com/.extraheader
          git remote set-url origin https://x-access-token:${{ secrets.ACTIONS_COMMMIT_TOKEN }}@github.com/${{ github.repository }}.git

      - name: Push main branch to tag
        run: |
          git fetch --tags
          git checkout main
          echo "Updating tag ${{ env.LATEST_TAG }} to point to latest commit on main"
          git push origin HEAD:refs/tags/${{ env.LATEST_TAG }} --force
