# shellcheck shell=dash

___x_cmd_feishu_group_ls(){
    local sort="ByCreateTimeAsc"
    local page="20"
    local format=;
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help)
                    ___x_cmd help -m feishu group ls; return 0 ;;
            --json)  format="json";    shift    ;;
            --sort)  sort="$2";   arg:2:shift    ;;
            --page)  page="$2";   arg:2:shift    ;;
           *)        N=feishu M="Unknown op -> $1" log:ret:64   ;;
        esac
    done

    local x_=""  cur_token=""
    ____x_cmd_tenant_token || return $?
    cur_token="$x_"

    local resp
    resp="$(___x_cmd curl -s "https://open.feishu.cn/open-apis/im/v1/chats?page_size=${page}&sort_type=${sort}" \
                  -H "Authorization: Bearer $cur_token")"

    if [ "$format" = "json" ]; then
        printf "%s\n" "$resp"
    else
        printf "%s\n" "$resp" | ___x_cmd jo .data.items                                     \
                              | ___x_cmd jo 2c             .chat_id     .name  .description \
                              | ___x_cmd csv header --add   Chatid       Name   Description
    fi
}

