# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# FILE INFORMATION
# DEFGROUP: Gitea.Workflow
# INGROUP: MokoPlatform.Universal
# REPO: https://git.mokoconsulting.tech/MokoConsulting/mokoplatform
# PATH: /.mokogitea/workflows/rc-revert.yml
# VERSION: 09.23.00
# BRIEF: Rename rc/ branch back to dev/ when PR is closed without merge

name: "RC Revert"

on:
  pull_request:
    types: [closed]

env:
  FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true

jobs:
  revert:
    name: Rename rc/ back to dev/
    runs-on: ubuntu-latest
    if: >-
      github.event.pull_request.merged == false &&
      startsWith(github.event.pull_request.head.ref, 'rc/')

    steps:
      - name: Rename branch
        run: |
          BRANCH="${{ github.event.pull_request.head.ref }}"
          SUFFIX="${BRANCH#rc/}"
          DEV_BRANCH="dev/${SUFFIX}"
          API="${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}/api/v1/repos/${{ github.repository }}/branches"
          TOKEN="${{ secrets.MOKOGITEA_TOKEN }}"

          # Create dev/ branch from rc/ branch
          STATUS=$(curl -sf -o /dev/null -w "%{http_code}" -X POST \
            -H "Authorization: token ${TOKEN}" \
            -H "Content-Type: application/json" \
            -d "{\"new_branch_name\": \"${DEV_BRANCH}\", \"old_branch_name\": \"${BRANCH}\"}" \
            "${API}" 2>/dev/null || true)

          if [ "$STATUS" = "201" ]; then
            echo "Created branch: ${DEV_BRANCH}" >> $GITHUB_STEP_SUMMARY
          else
            echo "::error::Failed to create ${DEV_BRANCH} from ${BRANCH} (HTTP ${STATUS})"
            exit 1
          fi

          # Delete rc/ branch
          ENCODED=$(php -r "echo rawurlencode('${BRANCH}');")
          STATUS=$(curl -sf -o /dev/null -w "%{http_code}" -X DELETE \
            -H "Authorization: token ${TOKEN}" \
            "${API}/${ENCODED}" 2>/dev/null || true)

          if [ "$STATUS" = "204" ]; then
            echo "Deleted branch: ${BRANCH}" >> $GITHUB_STEP_SUMMARY
          else
            echo "::warning::Failed to delete ${BRANCH} (HTTP ${STATUS})"
          fi

          echo "### RC Reverted" >> $GITHUB_STEP_SUMMARY
          echo "${BRANCH} → ${DEV_BRANCH}" >> $GITHUB_STEP_SUMMARY
