#!/usr/bin/env bash
# gitea_list_repos — Lista repositorios de un owner (org o usuario) en Gitea

gitea_list_repos() {
    local owner="$1"

    if [[ -z "${GITEA_URL:-}" ]]; then
        echo "gitea_list_repos: GITEA_URL no está seteada" >&2
        return 1
    fi
    if [[ -z "${GITEA_TOKEN:-}" ]]; then
        echo "gitea_list_repos: GITEA_TOKEN no está seteado" >&2
        return 1
    fi
    if [[ -z "$owner" ]]; then
        echo "gitea_list_repos: se requiere owner" >&2
        return 1
    fi

    echo "gitea_list_repos: listando repos de '$owner' (intentando org)..." >&2

    local response http_code body
    response=$(curl -s -w "\n%{http_code}" \
        -H "Authorization: token ${GITEA_TOKEN}" \
        "${GITEA_URL}/api/v1/orgs/${owner}/repos?limit=50")

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

    if [[ "$http_code" != "200" ]]; then
        echo "gitea_list_repos: org no encontrada (${http_code}), intentando usuario..." >&2
        response=$(curl -s -w "\n%{http_code}" \
            -H "Authorization: token ${GITEA_TOKEN}" \
            "${GITEA_URL}/api/v1/users/${owner}/repos?limit=50")

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

        if [[ "$http_code" != "200" ]]; then
            echo "gitea_list_repos: error listando repos de usuario (HTTP ${http_code}): ${body}" >&2
            return 1
        fi
    fi

    # Formatear salida como name\thtml_url\tdescription
    if command -v jq &>/dev/null; then
        echo "$body" | jq -r '.[] | [.name, .html_url, (.description // "")] | @tsv'
    else
        # Fallback sin jq: extraer campos básicos con grep/sed
        echo "$body" | grep -o '"name":"[^"]*"\|"html_url":"[^"]*"\|"description":"[^"]*"' \
            | paste - - - | sed 's/"name":"//;s/"html_url":"//;s/"description":"//;s/"//g'
    fi
}
