#!/usr/bin/env bash
# gitea_create_repo — Crea un repositorio en Gitea para un owner (org o usuario)

gitea_create_repo() {
    local owner="$1"
    local name="$2"
    local private="${3:-false}"
    local description="${4:-}"

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

    local payload
    payload=$(printf '{"name":"%s","private":%s,"description":"%s","auto_init":false}' \
        "$name" "$private" "$description")

    echo "gitea_create_repo: intentando crear '$owner/$name' en org..." >&2

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

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

    if [[ "$http_code" == "201" ]]; then
        echo "gitea_create_repo: repo '$owner/$name' creado en org" >&2
        echo "$body"
        return 0
    fi

    if [[ "$http_code" == "409" ]]; then
        echo "gitea_create_repo: repo '$owner/$name' ya existe (409)" >&2
        echo "$body"
        return 0
    fi

    if [[ "$http_code" == "404" || "$http_code" == "422" ]]; then
        echo "gitea_create_repo: org no encontrada (${http_code}), intentando en usuario..." >&2
        response=$(curl -s -w "\n%{http_code}" \
            -X POST \
            -H "Content-Type: application/json" \
            -H "Authorization: token ${GITEA_TOKEN}" \
            -d "$payload" \
            "${GITEA_URL}/api/v1/user/repos")

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

        if [[ "$http_code" == "201" ]]; then
            echo "gitea_create_repo: repo '$owner/$name' creado en usuario" >&2
            echo "$body"
            return 0
        fi

        if [[ "$http_code" == "409" ]]; then
            echo "gitea_create_repo: repo '$owner/$name' ya existe (409)" >&2
            echo "$body"
            return 0
        fi

        echo "gitea_create_repo: error al crear en usuario (HTTP ${http_code}): ${body}" >&2
        return 1
    fi

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