#!/usr/bin/env bash
# gitea_add_collaborator — Añade un colaborador a un repositorio Gitea

gitea_add_collaborator() {
    local owner="$1"
    local repo="$2"
    local username="$3"
    local permission="${4:-admin}"

    if [[ -z "${GITEA_URL:-}" ]]; then
        echo "gitea_add_collaborator: GITEA_URL no está seteada" >&2
        return 1
    fi
    if [[ -z "${GITEA_TOKEN:-}" ]]; then
        echo "gitea_add_collaborator: GITEA_TOKEN no está seteado" >&2
        return 1
    fi
    if [[ -z "$owner" || -z "$repo" || -z "$username" ]]; then
        echo "gitea_add_collaborator: se requieren owner, repo y username" >&2
        return 1
    fi

    local payload
    payload=$(printf '{"permission":"%s"}' "$permission")

    echo "gitea_add_collaborator: añadiendo '$username' a '$owner/$repo' con permiso '$permission'..." >&2

    local response http_code
    response=$(curl -s -w "\n%{http_code}" \
        -X PUT \
        -H "Content-Type: application/json" \
        -H "Authorization: token ${GITEA_TOKEN}" \
        -d "$payload" \
        "${GITEA_URL}/api/v1/repos/${owner}/${repo}/collaborators/${username}")

    http_code=$(echo "$response" | tail -n1)
    local body
    body=$(echo "$response" | head -n -1)

    if [[ "$http_code" == "204" || "$http_code" == "200" ]]; then
        echo "gitea_add_collaborator: '$username' añadido a '$owner/$repo'" >&2
        return 0
    fi

    if [[ "$http_code" == "422" ]]; then
        echo "gitea_add_collaborator: '$username' ya es colaborador de '$owner/$repo' (silencioso)" >&2
        return 0
    fi

    echo "gitea_add_collaborator: error (HTTP ${http_code}): ${body}" >&2
    return 1
}
