name: 'Release: Merge tag to branch'
run-name: 'Merge n8n@${{ inputs.version }} to ${{ inputs.target-branch }}'

on:
  workflow_call:
    inputs:
      version:
        description: 'The release version (e.g. 2.10.2)'
        required: true
        type: string
      target-branch:
        description: 'The branch to merge the release tag into (e.g. master or release-candidate/2.10.x)'
        required: true
        type: string

jobs:
  merge-tag-to-branch:
    name: Merge release tag to ${{ inputs.target-branch }}
    runs-on: ubuntu-latest
    environment: minor-release-tag-merge
    env:
      VERSION: ${{ inputs.version }}
      TARGET_BRANCH: ${{ inputs.target-branch }}
    steps:
      - name: Generate GitHub App Token
        id: generate_token
        uses: actions/create-github-app-token@29824e69f54612133e76f7eaac726eef6c875baf # v2.2.1
        with:
          app-id: ${{ secrets.RELEASE_TAG_MERGE_APP_ID }}
          private-key: ${{ secrets.RELEASE_TAG_MERGE_PRIVATE_KEY }}
          skip-token-revoke: false

      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          ref: ${{ inputs.target-branch }}
          fetch-depth: 500
          token: ${{ steps.generate_token.outputs.token }}

      - name: Verify release tag exists
        run: |
          if ! git ls-remote --tags origin "refs/tags/n8n@${VERSION}" | grep -q .; then
            echo "::error::Tag n8n@${VERSION} not found on remote"
            exit 1
          fi

      - name: Fetch release tag
        run: git fetch origin "refs/tags/n8n@${VERSION}:refs/tags/n8n@${VERSION}"

      - name: Merge release tag to branch
        run: |
          git config user.name "n8n-release-tag-merge[bot]"
          git config user.email "256767729+n8n-release-tag-merge[bot]@users.noreply.github.com"
          git merge --ff "n8n@${VERSION}"

      - name: Push to ${{ inputs.target-branch }}
        run: git push origin "HEAD:${TARGET_BRANCH}"

  notify-on-failure:
    name: Notify Slack on failure
    needs: [merge-tag-to-branch]
    if: ${{ always() && needs.merge-tag-to-branch.result == 'failure' }}
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          ref: master
          sparse-checkout: .github/scripts/slack
          sparse-checkout-cone-mode: false
      - name: Notify Slack
        env:
          SLACK_TOKEN: ${{ secrets.QBOT_SLACK_TOKEN }}
          TARGET_BRANCH: ${{ inputs.target-branch }}
          VERSION: ${{ inputs.version }}
          RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
        run: |
          node .github/scripts/slack/notify.mjs \
            --channel '#updates-and-product-releases' \
            --text "<${RUN_URL}|Release tag merge to ${TARGET_BRANCH} failed for n8n@${VERSION}>"
