# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# FILE INFORMATION
# DEFGROUP: Gitea.Workflow
# INGROUP: MokoStandards.Universal
# REPO: https://git.mokoconsulting.tech/MokoConsulting/moko-platform
# PATH: /.mokogitea/workflows/branch-cleanup.yml
# VERSION: 01.00.00
# BRIEF: Delete feature branches after PR merge

name: "Branch Cleanup"

on:
  pull_request:
    types: [closed]

env:
  FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true

jobs:
  cleanup:
    name: Delete merged branch
    runs-on: ubuntu-latest
    if: >-
      github.event.pull_request.merged == true &&
      github.event.pull_request.head.ref != 'dev' &&
      github.event.pull_request.head.ref != 'main'

    steps:
      - name: Delete source branch
        run: |
          BRANCH="${{ github.event.pull_request.head.ref }}"
          API="${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}/api/v1/repos/${{ github.repository }}/branches"
          ENCODED=$(php -r "echo rawurlencode('${BRANCH}');")

          STATUS=$(curl -sf -o /dev/null -w "%{http_code}" -X DELETE \
            -H "Authorization: token ${{ secrets.MOKOGITEA_TOKEN }}" \
            "${API}/${ENCODED}" 2>/dev/null || true)

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