# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# FILE INFORMATION
# DEFGROUP: Gitea.Workflow
# INGROUP: mokoplatform.Automation
# VERSION: 06.14.00
# BRIEF: Auto-create feature branch when an issue is opened

name: "Universal: Issue Branch"

on:
  issues:
    types: [opened]

permissions:
  contents: write
  issues: write

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

jobs:
  create-branch:
    name: Create feature branch
    runs-on: ubuntu-latest
    steps:
      - name: Create branch and comment
        run: |
          TOKEN="${{ secrets.MOKOGITEA_TOKEN }}"
          API="${GITEA_URL}/api/v1/repos/${{ github.repository }}"
          ISSUE_NUM="${{ github.event.issue.number }}"
          ISSUE_TITLE="${{ github.event.issue.title }}"

          # Build slug from title: lowercase, replace non-alnum with dash, trim
          SLUG=$(echo "${ISSUE_TITLE}" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//' | cut -c1-40)
          BRANCH="feature/${ISSUE_NUM}-${SLUG}"

          # Check dev branch exists
          DEV_EXISTS=$(curl -sf -o /dev/null -w '%{http_code}' \
            -H "Authorization: token ${TOKEN}" \
            "${API}/branches/dev" 2>/dev/null || echo "000")

          if [ "${DEV_EXISTS}" != "200" ]; then
            echo "No dev branch -- skipping"
            exit 0
          fi

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

          if [ "${HTTP}" = "201" ]; then
            echo "Created branch: ${BRANCH}"

            # Comment on issue with branch link
            REPO_URL="${GITEA_URL}/${{ github.repository }}"
            BODY="Branch created: [\`${BRANCH}\`](${REPO_URL}/src/branch/${BRANCH})\n\n\`\`\`bash\ngit fetch origin\ngit checkout ${BRANCH}\n\`\`\`"

            curl -sf -X POST \
              -H "Authorization: token ${TOKEN}" \
              -H "Content-Type: application/json" \
              "${API}/issues/${ISSUE_NUM}/comments" \
              -d "{\"body\":\"${BODY}\"}" > /dev/null 2>&1

            echo "Commented on issue #${ISSUE_NUM}"
          else
            echo "Failed to create branch (HTTP ${HTTP}) -- may already exist"
          fi
