# shellcheck shell=sh
# shellcheck disable=SC2039,SC3043,SC2034

# Section: Fork
# https://docs.github.com/en/rest/repos/forks#create-a-fork
# shellcheck disable=2154
___x_cmd_gh_repo_fork(){
    param:scope ___x_cmd_github
    param:dsl '
options:
    #1                          "Target repo <ownerPath>/<RepoPath>"                           <>
    --org                       "Forking into an organization"                                 <>=""
    --name                      "A new name for the fork repository"                           <>=""
    --all_branch                "Fork with the all branch"
    --json|-j                   "output json data"
'
    param:run
    local gen_gh_json=
    gen_gh_json="$(param:option2json -org ${org:+"organization=org"} 'default_branch_only=^all_branch')"
    gh:debug "$gen_gh_json"

    local repo="$1"
    ___x_cmd_gh_param_init_owner_repo
    ___x_cmd_gh_curl post "/repos/${owner_repo}/forks" "gen_gh_json" | ___x_cmd_gh_repo_fork____ui_handler

}

___x_cmd_gh_repo_fork____ui_handler(){
    if [ -n "$ENFORCE_JSON" ] || [ -n "$json" ]; then
        ___x_cmd_cmds_cat
        ___x_cmd_gh_http_error
        return
    fi
    (
        local _name=""
        x jo env . _name=.full_name html_url=.html_url gh_resp_msg=.message gh_resp_err=.errors
        if [ -n "$_name" ]; then
            ___x_cmd_ui_tf  true "Forking $owner_repo successfully, You may have to wait a short period of time before you can access the git objects:" \
                ${_name:+"Path: $_name"}  ${html_url:+"URL: $html_url"}
        else
            ___x_cmd_ui_tf false "Forking $owner_repo failure:" >&2
            ___x_cmd_gh____handle_resp
        fi
    )
}
# EndSection

# Section: Clone
___x_cmd_gh_repo_cl(){
    param:void
    if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then _____x_cmd_gh_help repo clone; return;
    fi

    local _domain=""; _domain="$(___x_cmd_gh___get_web_endpoint)"; _domain="${_domain#*'://'}";
    ___X_CMD_GIT_CLONE_HOST="$_domain" x git clone "$@"
}
# EndSection

# Section: Browse
___x_cmd_gh_browse(){
    param:scope ___x_cmd_github
    param:dsl <<A
options:
    #1                 "Issue or pull request number"                                  <>=""
    --repo|-r          "<owner_path>/<repo_path>"                                      <>:RepoName=""
    --no_browser|-n    "Print destination URL instead of opening the browser"
A
    param:run
    local _endpoint=""; _endpoint=$(___x_cmd_gh___get_web_endpoint)

    ___x_cmd_gh_param_init_owner_repo
    local _url=""
    if [ -n "$1" ]; then
        [ -n "$owner_repo" ] || M='accepts option --repo|-r (<owner>/<repo>), received empty' arg:ret:64
        _url="${_endpoint}/${owner_repo}/issues/$1"
    else
        [ -n "$owner_repo" ] || owner_repo="$(___x_cmd_gh_cfg get owner 2>/dev/null)"
        _url="${_endpoint}/${owner_repo}"
    fi

    if [ -n "$no_browser" ]; then
        printf "%s\n" "$_url";
    else
        x open "$_url";
    fi
}
# EndSection
