# shellcheck shell=dash

___x_cmd_hub_account_bind(){
    local X_help_cmd='___x_cmd_hub___help account bind'
    help:arg-null:parse

    local op="$1"; [ $# -eq 0 ] || shift
    case "$op" in
        email|tg)      ___x_cmd_hub_account_bind_"$op"      "$@" ;;
        *)          ___x_cmd_hub_u_subcmd_invalid bind   "$@" ;;
    esac
}

# TODO: avoid use subshell
___x_cmd_hub_account_bind_email()(
    local X_help_cmd='___x_cmd_hub___help account bind email'
    help:arg:parse

    local token ; token="$(___x_cmd_hub_u_get_token)" || return

    local email="$1"
    if [ -z "$email" ]; then
        if ! ___x_cmd_runmode_allow_manual ; then
            hub:error "Email required, but not in interactive tty"
            return 1
        fi

        ___X_CMD_TUI_FORM_FINAL_COMMAND=""
        ___x_cmd tui form email      "Email"           ""  '=~'  '^.*@.*$' || return 1
        [ -n "$___X_CMD_TUI_FORM_FINAL_COMMAND" ] || {
            hub:info "Canceled"
            return 1
        }
    fi
    ___x_cmd_hub_account_bind_email___witharg "$email"
)

___x_cmd_hub_account_bind_tg()(
    local X_help_cmd='___x_cmd_hub___help account bind tg'
    help:arg:parse

    local token ; token="$(___x_cmd_hub_u_get_token)" || return
    local ticket; ticket="$(___x_cmd_hub_u_ticket_generate)"
    local ___X_CMD_HUB_SERVICE_URL="https://cf-hub.it-9b9.workers.dev/api/v0"
    ___x_cmd_hub_u_curl get /account/bind/tg?ticket="$ticket" >/dev/null || {
        ___x_cmd_hub_u_handle_resp false "Unable to get Telegram binding information."
        return 1
    }
    local url="https://t.me/ljh_xcmd_bot?start=@hub_bind${ticket}"
    ___x_cmd_hub_qrcode "$url"
    hub:info "请在浏览器中打开 ${url} 或者扫描二维码添加x-cmd机器人，并在5分钟内发送 \`@hub_bind${ticket}\` 完成绑定验证。"
)
___x_cmd_hub_account_bind_email___witharg(){
    local email="$1"
    [ -n "$email" ] || M='Provide email' N=hub log:ret:64

    # Send email
    local resp=
    resp="$(___x_cmd_hub_u_curl post /api/v0/account/email/bind -- "email=$email")" || {
        ___x_cmd_hub_u_handle_resp false "Failed to bind with email $email:"
        return 1
    }
    hub:debug "Bind with $email, resp => $resp"
    ___x_cmd_ui_tf true "Verification Email Sent to $email ! Please check your email inbox (including the spam folder) to complete the verification process."
    ___x_cmd ui yesno "Email Verified" || return 1

    # Check email is binded
    ___x_cmd_hub_u_curl get /api/v0/account | {
        local remote_email=; local msg=
        ___x_cmd jo env . remote_email=.email .msg
        [ -n "$remote_email" ] || {
            ___x_cmd_hub_u_handle_resp false "Failed to get user info:"
            return 1
        }

        if [ "$email" != "$remote_email" ]; then
            ___x_cmd_hub_u_handle_resp false "$email" "Failed to bind with email $email:"
            return 1
        fi

        ___x_cmd_hub_u_handle_resp true "Successfully bind with email $remote_email"
    }
}
