# shellcheck shell=sh
# shellcheck disable=SC2039,3043,2034
# https://docs.gitlab.com/ee/api/merge_requests.html
___x_cmd_gl_repo_mr(){
    param:scope         ___x_cmd_gl
    param:subcmd ___x_cmd_gl_repo_mr             \
        ls              "List merge requests"       \
        info            "Merge requests info"       \
        create          "Create merge requests"     \
        "edit|ed"       "Edit merge requests"       \
        merge           "Merge merge requests"      \
        rm              "Delete merge requests"
    param:subcmd:try
    param:run

    ___x_cmd_gl_repo_mr _param_help_doc
    return 1
}

# Section: List
# https://docs.gitlab.com/ee/api/merge_requests.html#list-project-merge-requests
___x_cmd_gl_repo_mr_ls(){
    param:scope     ___x_cmd_gl
    param:dsl       '
options:
    --repo|-r                     "<owner_path>/<repo_path> or .id=<repo_id>"                                                              <>
    --state                       "Return all merge requests or just those that are opened, closed, locked, or merged"                     <>=""     = "opened" "closed" "locked" "merged"
    --labels                      "Return merge requests matching a comma-separated list of labels"                                        <>=""
    --sort                        "Return requests sorted in asc or desc order"                                                            <>="desc" = asc desc
    --order_by                    "Return requests ordered by created_at or updated_at fields"                                             <>="created_at" = "created_at" "updated_at"
    --scope                       "Return merge requests for the given scope: created_by_me, assigned_to_me or all"                        <>=""   = "created_by_me" "assigned_to_me" "all"
    --milestone                   "Return merge requests for a specific milestone"                                                         <>=""
    --search                      "Search merge requests against their title and description"                                              <>=""
    --target_branch               "Return merge requests with the given target branch"                                                     <>=""
    --source_branch               "Return merge requests with the given source branch"                                                     <>=""
    --author_id                   "Return prs created by the given user id"                                                                <>:Number=""
    --assignee_id                 "Returns merge requests assigned to the given user id"                                                   <>:Number=""
    --approver_ids                "Returns merge requests which have specified all the users with the given id as individual approvers"    <>:array=""
    --author_username             "Return prs created by the given username"                                                               <>=""
    --page                        "target page"                                                                                            <>:Per_page="1"
    --per_page                    "per page data number"                                                                                   <>:Numbers="30"
    --json|-j                     "output raw JSON data"

    --wip                         "Filter merge requests against their wip status"                                                                                             <>=""
    --view                        "If simple, returns the iid, URL, title, description, and basic state of merge request"                                                      <>=""
    --iids                        "Return the request having the given iid"                                                                                                    <>:array=""
    --created_before              "Return merge requests created on or before the given time"                                                                                  <>:datetime=""
    --created_after               "Return merge requests created on or after the given time. Expected in ISO 8601 format"                                                      <>:datetime=""
    --updated_after               "Return prs updated on or after the given time"                                                                                              <>:datetime=""
    --updated_before              "Return prs updated on or before the given time"                                                                                             <>:datetime=""
    --approved_by_ids             "Returns merge requests which have been approved by all the users with the given id, with a maximum of 5"                                    <>:array=""
    --my_reaction_emoji           "Return merge requests reacted by the authenticated user by the given emoji"                                                                 <>=""
    --with_labels_details         "If true, the response returns more details for each label in labels field: :name, :color, :description, :description_html,:text_color"      <>:bool="false"  = true false
    --with_merge_status_recheck   "If true, this projection requests (but does not guarantee) that the merge_status field be recalculated asynchronously"                      <>:bool="false"  = true false
'
    param:run

    ___x_cmd_gl_param_init_owner_repo
    if [ -n "$json" ] || [ -n "$ENFORCE_JSON" ]; then
        ___x_cmd_gl_get_multi "/projects/${owner_repo}/merge_requests" sort order_by search state labels source_branch target_branch
    else
        ___x_cmd_gl_get_multi "/projects/${owner_repo}/merge_requests" sort order_by search state labels source_branch target_branch | \
            x jo 2c .id .iid .project_id .title .state .web_url | \
            x csv header --add ID IID Project_ID Title State URL | \
            x csv static_tab
    fi
}
# EndSection

# Section: Info
# https://docs.gitlab.com/ee/api/merge_requests.html#get-single-mr
___x_cmd_gl_repo_mr_info(){
    param:scope     ___x_cmd_gl
    param:dsl      '
options:
    #1                                 "The internal ID of the merge request"                                                 <>
    --repo|-r                          "<owner_path>/<repo_path> or .id=<repo_id>"                                            <>
    --render_html                      "If true, response includes rendered HTML for title and description"
    --include_diverged_commits_count   "If true, response includes the commits behind the target branch"
    --include_rebase_in_progress       "If true, response includes whether a rebase operation is in progress"

    --json|-j                          "output raw JSON data"

'
    param:run
    ___x_cmd_gl_param_init_owner_repo
    ___x_cmd_gl_curl get "/projects/$owner_repo/merge_requests/$1" | _____x_cmd_gl_repo_pr_ui_utils Info
}

# EndSection

# Section: Create
# https://docs.gitlab.com/ee/api/merge_requests.html#create-mr
___x_cmd_gl_repo_mr_create(){
    param:scope     ___x_cmd_gl
    param:dsl       '
options:
    --repo|-r                     "<owner_path>/<repo_path> or .id=<repo_id>"                                                               <>
    --source_branch               "Return merge requests with the given source branch"                                                      <>
    --target_branch               "Return merge requests with the given target branch"                                                      <>
    --title                       "Title of MR"                                                                                             <>
    --allow_collaboration         "Allow commits from members who can merge to the target branch"
    --allow_maintainer_to_push    "Alias of allow_collaboration"
    --approvals_before_merge      "Number of approvals required before this can be merged"                                                  <>:Number=""
    --assignee_id                 "Assignee user ID"                                                                                        <>:Number=""
    --assignee_ids                "The ID of the users to assign the MR to. Set to 0 or provide an empty value to unassign all assignees"   <>:array=""
    --description                 "Description of the merge request"                                                                        <>=""
    --labels                      "Labels for the merge request, as a comma-separated list"                                                 <>=""
    --milestone_id                "The global ID of a milestone"                                                                            <>:Number=""
    --remove_source_branch        "Flag indicating if a merge request should remove the source branch when merging"
    --reviewer_ids                "The ID of the users added as a reviewer to the merge request"                                            <>:array=""
    --squash                      "Squash commits into a single commit when merging"
    --target_project_id           "Numeric ID of the target project"                                                                        <>:Number=""
    --json|-j                     "output raw JSON data"
'
    param:run

    local gen_gl_json
    gen_gl_json="$(param:option2json -repo)"
    gl:debug "$gen_gl_json"
    ___x_cmd_gl_param_init_owner_repo

    ___x_cmd_gl_curl post "/projects/$owner_repo/merge_requests" "gen_gl_json" | _____x_cmd_gl_repo_mr_ui_utils Creating
}
# EndSection

# Section: Edit
# https://docs.gitlab.com/ee/api/merge_requests.html#update-mr
___x_cmd_gl_repo_mr_edit(){
    param:scope     ___x_cmd_gl
    param:dsl       '
options:
    #1                            "The ID of a merge request"                                                                                          <>
    --repo|-r                     "<owner_path>/<repo_path> or .id=<repo_id>"                                                                          <>
    --title                       "Title of MR"                                                                                                        <>
    --add_labels                  "Comma-separated label names to add to a merge request"                                                              <>=""
    --allow_collaboration         "Allow commits from members who can merge to the target branch"
    --allow_maintainer_to_push    "Alias of allow_collaboration"
    --assignee_id                 "The ID of the user to assign the merge request to. Set to 0 or provide an empty value to unassign all assignees"    <>:Number=""
    --assignee_ids                "The ID of the users to assign the merge request to. Set to 0 or provide an empty value to unassign all assignees"   <>:array=""
    --description                 "Description of the merge request"                                                                                   <>=""
    --discussion_locked           "Flag indicating if the merge request discussion is locked"
    --labels                      "Comma-separated label names for a merge request"                                                                    <>=""
    --milestone_id                "The global ID of a milestone to assign the merge request to"                                                        <>:Number=""
    --remove_source_branch        "Flag indicating if a merge request should remove the source branch when merging"
    --remove_labels               "Comma-separated label names to remove from a merge request"                                                         <>=""
    --reviewer_ids                "The ID of the users added as a reviewer to the merge request"                                                       <>:array=""
    --squash                      "Squash commits into a single commit when merging"
    --state_event                 "New state (close/reopen)"                                                                                           <>=""
    --target_branch               "The target branch"                                                                                                  <>=""
    --json|-j                     "output raw JSON data"
'
    param:run
    local gen_gl_json
    gen_gl_json="$(param:option2json -repo)"
    gl:debug "$gen_gl_json"

    ___x_cmd_gl_param_init_owner_repo
    ___x_cmd_gl_curl put "/projects/$owner_repo/merge_requests/$1" "gen_gl_json" | _____x_cmd_gl_repo_mr_ui_utils Edit
}
# EndSection

# Section: Merge
# https://docs.gitlab.com/ee/api/merge_requests.html#merge-a-merge-request
___x_cmd_gl_repo_mr_merge() {
    param:scope     ___x_cmd_github
    param:dsl       '
options:
    #1                              "The ID of a merge request"                                                                        <>
    --repo|-r                       "<owner_path>/<repo_path> or .id=<repo_id>"                                                        <>
    --merge_commit_message          "Custom merge commit message"                                                                      <>=""
    --merge_when_pipeline_succeeds  "If true, the merge request is merged when the pipeline succeeds"
    --sha                           "If present, then this SHA must match the HEAD of the source branch, otherwise the merge fails"    <>=""
    --should_remove_source_branch   "If true, removes the source branch"
    --squash_commit_message         "Custom squash commit message"                                                                     <>=""
    --squash                        "If true, the commits are squashed into a single commit on merge"                                  <>=""
    --json|-j                       "output raw JSON data"
'
    param:run

    ___x_cmd_gl_param_init_owner_repo
    local gen_gl_json
    gen_gl_json="$(param:option2json -repo)"
    gl:debug "$gen_gl_json"

    ___x_cmd_gl_curl put "/projects/$owner_repo/merge_requests/$1/merge" "gen_gl_json" | _____x_cmd_gl_repo_mr_ui_utils Merge
}

# EndSection

# Section: Remove
# https://docs.gitlab.com/ee/api/merge_requests.html#delete-a-merge-request
___x_cmd_gl_repo_mr_rm(){
    param:scope     ___x_cmd_gl
    param:dsl       '
options:
    #1              "The internal ID of the merge request."                 <>
    --repo|-r       "<owner_path>/<repo_path> or .id=<repo_id>."            <>

    --yes|-y        "Ignore remove prompt interception"
'
    param:run

    ___x_cmd_gl_param_init_owner_repo
    [ "$yes" = "true" ] || ___x_cmd_ui_yesno "Are you sure you want to delete merge request : $(___x_cmd_ui bold red "$1") ?" || return 0

    ___x_cmd_gl_curl del "/projects/$owner_repo/merge_requests/$1" | (
        x jo env . gl_resp_err=.error gl_resp_msg=.message
        if ___x_cmd_gl_http_error; then
            ___x_cmd_ui_tf  true "[Success]: Deleted $1 merge request"
        else
            ___x_cmd_ui_tf false "Delete $1 merge request failure:"
            ___x_cmd_gl____handle_resp
            return 1
        fi
    )
}
# EndSection

# Section: UI utils
_____x_cmd_gl_repo_mr_ui_utils(){
    if [ -n "$ENFORCE_JSON" ] || [ -n "$json" ]; then
        ___x_cmd_cmds_cat
        ___x_cmd_gl_http_error
        return
    fi
    (
        case "$1" in
            Info)
                _inf_msg="Getting Merge Request information successfully"
                _err_msg="Getting Merge Request information failure"
                ;;
            Creating|Edit|Merge)
                _inf_msg="$1 Merge Request successfully"
                _err_msg="$1 Merge Request failure"
                ;;
        esac
        local _id=""
        x jo env . _id=.id gl_resp_err=.error gl_resp_msg=.message \
            iid=.iid title=.title state=.state url=.web_url author=.author.username
        if [ -n "$_id" ]; then
            ___x_cmd_ui_tf  true "${_inf_msg}:" "ID: $_id" ${iid+"IID: $iid"} ${title+"Title: $title"} ${state+"State: $state"} ${author+"Author: $author"} ${url+"Url: $url"}
        else
            ___x_cmd_ui_tf false "${_err_msg}:"
            ___x_cmd_gl____handle_resp
            return 1
        fi
    )
}

# EndSection