#!/usr/bin/env bash
# gitea_create_webhook — Crea un webhook de push en un repositorio Gitea
set -euo pipefail

gitea_create_webhook() {
    local owner="$1"
    local repo="$2"
    local target_url="$3"
    local secret="${4:-}"

    if [[ -z "$owner" || -z "$repo" || -z "$target_url" ]]; then
        echo "usage: gitea_create_webhook <owner> <repo> <target_url> [secret]" >&2
        return 1
    fi

    local gitea_url="${GITEA_URL:?GITEA_URL no seteada}"
    local gitea_token="${GITEA_TOKEN:?GITEA_TOKEN no seteada}"

    # Payload JSON para el webhook
    local payload
    payload=$(cat <<EOF
{
    "type": "gitea",
    "active": true,
    "events": ["push"],
    "config": {
        "url": "$target_url",
        "content_type": "json",
        "secret": "$secret"
    }
}
EOF
)

    local response http_code body
    response=$(curl -s -w "\n%{http_code}" \
        -X POST \
        -H "Authorization: token $gitea_token" \
        -H "Content-Type: application/json" \
        -d "$payload" \
        "${gitea_url}/api/v1/repos/${owner}/${repo}/hooks")

    http_code=$(echo "$response" | tail -1)
    body=$(echo "$response" | sed '$d')

    if [[ "$http_code" -ge 200 && "$http_code" -lt 300 ]]; then
        # Extraer webhook ID del response
        local webhook_id
        webhook_id=$(echo "$body" | grep -oP '"id":\s*\K[0-9]+' | head -1)
        printf '{"webhook_id":%s,"owner":"%s","repo":"%s","target_url":"%s"}\n' \
            "$webhook_id" "$owner" "$repo" "$target_url"
    else
        echo "gitea_create_webhook: HTTP $http_code — $body" >&2
        return 1
    fi
}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
    gitea_create_webhook "$@"
fi
