# shellcheck shell=dash

___x_cmd_feishu_bot___send_json() {
    local req_json; req_json="$(___x_cmd_cmds_cat)"
    feishu:debug "$(printf "%s" "$req_json" | ___x_cmd jo fmt)"

    [ -n "$webhook" ] || {
        local webhook
        ___x_cmd_feishu_cur webhook:= 2>/dev/null
        [ -n "$webhook" ] || N=feishu M="Please setting up your webhook first ==> 'x feishu --cfg webhook=<your webhook url>'" log:ret:1
    }

    feishu:debug "$webhook"
    ___x_cmd curl -s -X POST                                \
                  -H 'Content-Type: application/json'       \
                  -d "$req_json"                            \
                  "$webhook?wait=true"
}

____x_cmd_tenant_token() {
    local cur_app_id=
    local cur_app_secret=

    ___x_cmd_feishu_cur cur_app_id:=app_id cur_app_secret:=app_secret 2>/dev/null

    [ -n "$cur_app_id" ] || N=feishu M="Please use 'x feishu login' to configure the Feishu bot's app_id and app_secret." log:ret:1

    x_="$(___x_cmd curl -s -X POST \
        "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/" \
        -H "Content-Type: application/json" \
        -d "{\"app_id\":\"$cur_app_id\",\"app_secret\":\"$cur_app_secret\"}" \
        | ___x_cmd jq -r '.tenant_access_token')"
}

___x_cmd_feishu_isready(){
    param:void

    local cur_app_id
    local cur_app_secret
    ___x_cmd_feishu_cur cur_app_id:=app_id cur_app_secret:=app_secret 2>/dev/null

    [ -n "$cur_app_id" ] && [ -n "$cur_app_secret" ]
}

___x_cmd_feishu_ensureinit(){
    if ! ___x_cmd_feishu_isready; then
        feishu:warn --cmd "x feishu login" "Please use 'x feishu login' to configure the Feishu bot's app_id and app_secret."
        ___x_cmd feishu login || return $?
    fi
}
