#!/bin/bash
# ========== api.sh ==========
# API функции для работы с панелью

# ---------- ЗАГРУЗКА ТОКЕНА ----------
get_panel_token() {
    if [[ -n "$SELECTED_PANEL_TOKEN" ]]; then
        echo "$SELECTED_PANEL_TOKEN"
    else
        echo ""
    fi
}

# ---------- ЗАПРОС К API ----------
make_api_request() {
    local method="$1"
    local url="$2"
    local token="$3"
    local data="$4"
    
    if [[ -z "$data" ]]; then
        curl -s -X "$method" "$url" \
            -H "Authorization: Bearer $token" \
            -H "Content-Type: application/json" 2>/dev/null
    else
        curl -s -X "$method" "$url" \
            -H "Authorization: Bearer $token" \
            -H "Content-Type: application/json" \
            -d "$data" 2>/dev/null
    fi
}

# ---------- ПРОВЕРКА КОНФИГУРАЦИЙ ----------
get_config_profiles() {
    local token="$1"
    local domain_url="${2:-127.0.0.1:3000}"
    
    make_api_request "GET" "${domain_url}/api/config-profiles" "$token"
}

# ---------- ПОЛУЧЕНИЕ КОНКРЕТНОЙ КОНФИГУРАЦИИ ----------
get_config_profile() {
    local uuid="$1"
    local token="$2"
    local domain_url="${3:-127.0.0.1:3000}"
    
    make_api_request "GET" "${domain_url}/api/config-profiles/$uuid" "$token"
}

# ---------- ОБНОВЛЕНИЕ КОНФИГУРАЦИИ ----------
update_config_profile() {
    local uuid="$1"
    local config_json="$2"
    local token="$3"
    local domain_url="${4:-127.0.0.1:3000}"
    
    local data="{\"uuid\": \"$uuid\", \"config\": $config_json}"
    make_api_request "PATCH" "${domain_url}/api/config-profiles" "$token" "$data"
}
