# shellcheck shell=dash
xrc ourl

___x_cmd_openrouter_credits(){
    local format=yml
    local op="$1";
    case "$op" in
        -j|--json)  shift; format=json      ;;
        -y|--yml)   shift; format=yml       ;;
        -h|--help)  shift; ___x_cmd help -m openrouter credits "$@"; return ;;
    esac

    ___x_cmd_openrouter_credits_"${format}" "$@"
}

___x_cmd_openrouter_credits_yml(){
    local data; data="$( ___x_cmd_openrouter_credits_raw )" || ourl:data:ret
    ___x_cmd_pipevar data ___x_cmd j2y
}

___x_cmd_openrouter_credits_json(){
    local data; data="$( ___x_cmd_openrouter_credits_raw )" || ourl:data:ret
    ___x_cmd_pipevar data ___x_cmd jo fmt
}

___x_cmd_openrouter_credits_raw(){
    ___x_cmd_openrouter_has_apikey || return $?

    local apikey=
    ___x_cmd_openrouter_cur apikey:=  2>/dev/null
    local data=; data="$(
        ___x_cmd curl \
            -sS  "$___X_CMD_OPENROUTER_DEFAULT_ENDPOINT/v1/credits" \
            --header "Authorization: Bearer $apikey"
    )"

    [ -z "$(printf "%s\n" "$data" | ___x_cmd jo .error)" ] || {
        openrouter:error -m "$data"
        return 1
    }

    printf "%s\n" "$data"
}
