# shellcheck shell=sh
# shellcheck disable=SC2039,3043
___x_cmd_gcode_repo_mr(){
    param:scope         ___x_cmd_gcode
    param:subcmd ___x_cmd_gcode_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_gcode_repo_mr _param_help_doc
    return 1
}

# Section: List
# http://localhost:4000/13.7/ee/api/merge_requests.html#list-project-merge-requests
___x_cmd_gcode_repo_mr_ls(){
    param:scope     ___x_cmd_gcode
    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"
    --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                        "page"                                                                                                    <>:Per_page="1"
    --per_page                    "per_page"                                                                                                <>:Numbers="30"
    --json|-j                     "output 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."      <>:bole="false"
    --with_merge_status_recheck   "If true, the response returns more details for each label in labels field: :name, :color, :description, :description_html,:text_color."      <>:bole="false"
'
    param:run

    ___x_cmd_gcode_param_init_owner_repo
    if [ -n "$json" ] || [ -n "$ENFORCE_JSON" ]; then
        ___x_cmd_gcode_get_multi "/projects/${owner_repo}/merge_requests" state labels sort order_by scope milestone search target_branch source_branch author_id assignee_id approver_ids author_username
    else
        ___x_cmd_gcode_get_multi "/projects/${owner_repo}/merge_requests" state labels sort order_by scope milestone search target_branch source_branch author_id assignee_id approver_ids author_username | \
            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
# http://localhost:4000/13.7/ee/api/merge_requests.html#get-single-mr
___x_cmd_gcode_repo_mr_info(){
    param:scope     ___x_cmd_gcode
    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 json data"

'
    param:run
    ___x_cmd_gcode_param_init_owner_repo
    ___x_cmd_gcode_curl get "/projects/$owner_repo/merge_requests/$1" | _____x_cmd_gcode_repo_mr_ui_utils Info
}

# EndSection

# Section: Create
# http://localhost:4000/13.7/ee/api/merge_requests.html#create-mr
___x_cmd_gcode_repo_mr_create(){
    param:scope     ___x_cmd_gcode
    param:dsl       '
options:
    --repo|-r                     "<owner_path>/<repo_path> or .id=<repo_id>"                                                               <>
    --title                       "Title of MR."                                                                                            <>
    --source_branch               "The source branch."                                                                                      <>
    --target_branch               "The target branch."                                                                                      <>
    --labels                      "Labels for the merge request, as a comma-separated list."                                                <>=""
    --squash                      "Squash commits into a singcodee commit when merging."                                                    <>:bole=""
    --description                 "Description of the merge request."                                                                       <>=""
    --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=""
    --milestone_id                "The global ID of a milestone."                                                                           <>:Number=""
    --allow_collaboration         "Allow commits from members who can merge to the target branch."                                          <>:bole=""
    --remove_source_branch        "Flag indicating if a merge request should remove the source branch when merging"                         <>:bole=""
    --target_project_id           "Numeric ID of the target project."                                                                       <>:Number=""
    --json|-j                     "output json data"
'
    param:run

    local gen_gcode_json
    gen_gcode_json="$(param:option2json -repo)"
    ___x_cmd_gcode_param_init_owner_repo
    ___x_cmd_gcode_curl post "/projects/${owner_repo}/merge_requests" "gen_gcode_json" | _____x_cmd_gcode_repo_mr_ui_utils Creating
}
# EndSection

# Section: Edit
# http://localhost:4000/13.7/ee/api/merge_requests.html#update-mr
___x_cmd_gcode_repo_mr_edit(){
    param:scope     ___x_cmd_gcode
    param:dsl       '
options:
    #1                            "The ID of a merge request."                                                             <>
    --repo|-r                     "<owner_path>/<repo_path> or .id=<repo_id>"                                              <>
    --title                       "Title of MR."                                                                           <>=""
    --labels                      "Comma-separated label names for a merge request."                                       <>=""
    --squash                      "Squash commits into a singcodee commit when merging."                                   <>:bole=""
    --add_labels                  "Comma-separated label names to add to a merge request."                                 <>=""
    --state_event                 "New state (close/reopen). "                                                             <>=""
    --assignee_id                 "The ID of the user to assign the merge request to."                                     <>:Number=""
    --assignee_ids                "The ID of the users to assign the merge request to. "                                   <>:array=""
    --description                 "Description of the merge request."                                                      <>=""
    --milestone_id                "The gcodeobal ID of a milestone to assign the merge request to. "                       <>:Number=""
    --remove_labels               "Comma-separated label names to remove from a merge request. "                           <>=""
    --target_branch               "The target branch. "                                                                    <>=""
    --discussion_locked           "Flag indicating if the merge request discussion is locked. "                            <>:bole=""
    --allow_collaboration         "Allow commits from members who can merge to the target branch."                         <>:bole=""
    --remove_source_branch        "Flag indicating if a merge request should remove the source branch when merging. "      <>=""
    --json|-j                     "output json data"
'
    param:run
    local gen_gcode_json
    gen_gcode_json="$(param:option2json -repo)"

    ___x_cmd_gcode_param_init_owner_repo
    ___x_cmd_gcode_curl put "/projects/${owner_repo}/merge_requests/$1" "gen_gcode_json" | _____x_cmd_gcode_repo_mr_ui_utils Edit
}
# EndSection

# Section: Merge
# http://localhost:4000/13.7/ee/api/merge_requests.html#accept-mr
___x_cmd_gcode_repo_mr_merge() {
    param:scope     ___x_cmd_gcode
    param:dsl       '
options:
    #1                                 "The ID of a merge request."                                                                             <>
    --repo|-r                          "<owner_path>/<repo_path> or .id=<repo_id>"                                                              <>
    --sha                              " if present, then this SHA must match the HEAD of the source branch, otherwise the merge will fail."    <>=""
    --squash                           "If true, the commits are squashed into a singcodee commit on merge."
    --merge_commit_message             "Custom merge commit message."                                                                           <>=""
    --merge_when_pipeline_succeeds     "If true, the merge request is merged when the pipeline succeeds."
    --should_remove_source_branch      "If true, removes the source branch."
    --squash_commit_message            "Custom squash commit message."                                                                          <>=""
    --json|-j                          "output json data"
'
    param:run

    ___x_cmd_gcode_param_init_owner_repo
    local gen_gcode_json
    gen_gcode_json="$(param:option2json -repo)"
    ___x_cmd_gcode_curl put "/projects/${owner_repo}/merge_requests/$1/merge" "gen_gcode_json" | _____x_cmd_gcode_repo_mr_ui_utils Merge
}
# EndSection

# Section: Remove
# http://localhost:4000/13.7/ee/api/merge_requests.html#delete-a-merge-request
___x_cmd_gcode_repo_mr_rm(){
    param:scope     ___x_cmd_gcode
    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_gcode_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_gcode_curl del "/projects/${owner_repo}/merge_requests/$1" | (
        x jo env . gcode_resp_err=.error gcode_resp_msg=.message
        if ___x_cmd_gcode_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_gcode____handle_resp
            return 1
        fi
    )
}
# EndSection

# Section: UI utils
_____x_cmd_gcode_repo_mr_ui_utils(){
    if [ -n "$ENFORCE_JSON" ] || [ -n "$json" ]; then
        ___x_cmd_cmds_cat
        ___x_cmd_gcode_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 gcode_resp_err=.error gcode_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_gcode____handle_resp
            return 1
        fi
    )
}
# EndSection