# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# FILE INFORMATION
# DEFGROUP: Gitea.Workflow
# INGROUP: MokoStandards.Maintenance
# REPO: https://git.mokoconsulting.tech/MokoConsulting/MokoStandards
# PATH: /.gitea/workflows/cleanup.yml
# VERSION: 01.00.00
# BRIEF: Scheduled cleanup — delete merged branches and old workflow runs

name: "Universal: Repository Cleanup"

on:
  schedule:
    - cron: '0 3 * * 0'  # Weekly on Sunday at 03:00 UTC
  workflow_dispatch:

permissions:
  contents: write

env:
  GITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}

jobs:
  cleanup:
    name: Clean Merged Branches
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.MOKOGITEA_TOKEN }}

      - name: Delete merged branches
        env:
          GA_TOKEN: ${{ secrets.MOKOGITEA_TOKEN }}
        run: |
          echo "=== Merged Branch Cleanup ==="
          API="${GITEA_URL}/api/v1/repos/${{ github.repository }}"

          # List branches via API
          BRANCHES=$(curl -sS -H "Authorization: token ${GA_TOKEN}" \
            "${API}/branches?limit=50" | jq -r '.[].name')

          DELETED=0
          for BRANCH in $BRANCHES; do
            # Skip protected branches
            case "$BRANCH" in
              main|master|develop|release/*|hotfix/*) continue ;;
            esac

            # Check if branch is merged into main
            if git merge-base --is-ancestor "origin/${BRANCH}" origin/main 2>/dev/null; then
              echo "  Deleting merged branch: ${BRANCH}"
              curl -sS -X DELETE -H "Authorization: token ${GA_TOKEN}" \
                "${API}/branches/${BRANCH}" 2>/dev/null || true
              DELETED=$((DELETED + 1))
            fi
          done

          echo "Deleted ${DELETED} merged branch(es)"

      - name: Clean old workflow runs
        env:
          GA_TOKEN: ${{ secrets.MOKOGITEA_TOKEN }}
        run: |
          echo "=== Workflow Run Cleanup ==="
          API="${GITEA_URL}/api/v1/repos/${{ github.repository }}"
          CUTOFF=$(date -d "30 days ago" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -v-30d +%Y-%m-%dT%H:%M:%SZ)

          # Get old completed runs
          RUNS=$(curl -sS -H "Authorization: token ${GA_TOKEN}" \
            "${API}/actions/runs?status=completed&limit=50" | \
            jq -r ".workflow_runs[] | select(.created_at < \"${CUTOFF}\") | .id" 2>/dev/null)

          DELETED=0
          for RUN_ID in $RUNS; do
            curl -sS -X DELETE -H "Authorization: token ${GA_TOKEN}" \
              "${API}/actions/runs/${RUN_ID}" 2>/dev/null || true
            DELETED=$((DELETED + 1))
          done

          echo "Deleted ${DELETED} old workflow run(s)"
