# shellcheck shell=dash
# https://umami.is/docs/api
# Note: V1 API is deprecated due to security vulnerabilities. Use V2 API.
___x_cmd_umami_api(){
    local op="$1"; [ -n "$op" ] || return 1

    local _api_endpoint="${___X_CMD_UMAMI_ENDPOINT:-$(___x_cmd umami --cfg get endpoint 2>/dev/null)}"
    [ -n "$_api_endpoint" ] || M='Please configure API Endpoint.' N=umami log:ret:1
    local _auth_token="${___X_CMD_UMAMI_TOKEN:-$(___x_cmd umami --cfg get token 2>/dev/null)}"
    [ -n "$_auth_token" ]   || M='Please configure token.'        N=umami log:ret:1

    local _curl_header="${___X_CMD_UMAMI_HEADER:-"-H \"Accept:application/json\""}"
    # V2 API uses Bearer token for both cloud and self-hosted
    local _auth_header
    if [ -n "$_auth_token" ]; then
        _auth_header="-H \"Authorization: Bearer $_auth_token\""
    fi

    case "${op}" in
        get|put|patch|del)
            local _curl_url="${___X_CMD_UMAMI_ENDPOINT:-$_api_endpoint}$2" ; shift 2
            ___x_cmd_umami_api_"$op" "$_curl_url"
            ;;
        post)
            _curl_header="${_curl_header} -H \"Content-Type: application/json\""
            local _curl_url="${___X_CMD_UMAMI_ENDPOINT:-$_api_endpoint}$2" ; shift 2
            ___x_cmd_umami_api_"$op" "$_curl_url"
            ;;
        *)
            local _curl_url="${___X_CMD_UMAMI_ENDPOINT:-$_api_endpoint}$op"; shift 1
            ___x_cmd_umami_api_get "$_curl_url"
            ;;
    esac
}

___x_cmd_umami_api_get(){
    local _curl_url="$1"
    x curl -sS -L -X GET \
        -H "Accept: application/json" \
        -H "Authorization: Bearer $(x umami --cfg get token 2>/dev/null)" \
        "$_curl_url"
}

___x_cmd_umami_api_post(){
    local _curl_url="$1"
    x curl -sS -L -X POST \
        -H "Accept: application/json" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $(x umami --cfg get token 2>/dev/null)" \
        "$_curl_url"
}
