# shellcheck shell=sh
# shellcheck disable=SC2039,3043,2034
# https://docs.gitlab.com/ee/api/issues.html
___x_cmd_gl_issue(){
    param:scope         ___x_cmd_gl
    param:subcmd ___x_cmd_gl_issue                   \
        ls              "List repo issue"            \
        create          "Create repo issue"          \
        "edit|ed"       "Edit repo issue"            \
        rm              "Delete repo issue"          \
        close           "Close repo issue"           \
        reopen          "Reopen repo issue"
    param:subcmd:try
    param:run

    ___x_cmd_gl_issue _param_help_doc

    return 1
}

# Section: List
# TODO: user issue order_by type: created_at,due_date,label_priority,milestone_due,popularity,priority,relative_position,title, updated_at,or weight
# https://docs.gitlab.com/ee/api/issues.html#list-issues
___x_cmd_gl_issue_ls(){
    param:scope     ___x_cmd_gl
    param:dsl       '
options:
    --group|-g              "<group_path> or .id=<group_id>"                                                                                                    <>=""
    --repo|-r               "<owner_path>/<repo_path> or .id=<repo_id>"                                                                                         <>=""
    --state                 "Return all issues or just those that are opened or closed"                                                                         <>=""
    --sort                  "Return issues sorted in asc or desc order. Default is desc"                                                                        <>="desc" = "asc" "desc"
    --labels                "Comma-separated list of label names, issues must have all labels to be returned"                                                   <>=""
    --order_by              "Return issues ordered by fields. Default is created_at"                                                                            <>="created_at" = "created_at" "updated_at" "priority" "due_date" "relative_position" "label_priority" "milestone_due" "popularity" "weight"
    --milestone             "Returns issues assigned to milestones title (None, Any)"                                                                           <>=""
    --assignee_id           "Return issues assigned to the given user id"                                                                                       <>:Number=""
    --assignee_username     "Return issues assigned to the given username"                                                                                      <>:array=""
    --author_id             "Return issues created by the given user id."                                                                                       <>:Number=""
    --author_username       "Return issues created by the given username."                                                                                      <>=""
    --search                "Search issues against their title and description"                                                                                 <>=""
    --page                  "target page"                                                                                                                       <>:Per_page="1"
    --per_page              "per page data number"                                                                                                              <>:Numbers="30"
    --confidential          "Filter confidential or public issues."
    --json|-j               "output raw JSON data"


    --issue_type            "Filter to a given type of issue."                                                                                                                                          <>=""  = issue incident test_case
    --in                    "Modify the scope of the search attribute."                                                                                                                                 <>="title,description"  = title description string
    --created_after         "Return issues created on or after the given time. Expected in ISO 8601 format"                                                                                             <>:datetime=""
    --created_before        "Return issues created on or before the given time."                                                                                                                        <>:datetime=""
    --due_date              "Return issues that have no due date,are overdue,or whose due date is this week,this month,or between two weeks ago and next month"                                         <>=""
    --epic_id               "Return issues associated with the given epic ID."                                                                                                                          <>:Number=""
    --iids                  "Return only the issues having the given iid"                                                                                                                               <>:array=""
    --iteration_id          "Return issues assigned to the given iteration ID."                                                                                                                         <>:Number=""
    --iteration_title       "Return issues assigned to the iteration with the given title."                                                                                                             <>=""
    --my_reaction_emoji     "Return issues reacted by the authenticated user by the given emoji. "                                                                                                      <>=""
    --non_archived          "Return issues only from non-archived projects.If false,the response returns issues from both archived and non-archived projects.Default is true"                           <>="true"  = true false
    --not                   "Return issues that do not match the parameters supplied. "                                                                                                                 <>:hash=""
    --scope                 "Return issues for the given scope:"                                                                                                                                        <>=""
    --updated_after         "Return issues updated on or after the given time."                                                                                                                         <>:datetime=""
    --updated_before        "Return issues updated on or before the given time."                                                                                                                        <>:datetime=""
    --weight                "Return issues with the specified weight."                                                                                                                                  <>:Number=""
    --with_labels_details   "If true, the response returns more details for each label in labels field: :name, :color, :description, :description_html,:text_color.Default is false."                   <>="false"  = true false
'
    param:run
    local url="/issues"
    if [ -n "$repo" ]; then
        [ -z "$group" ] || M='only one of --repo <owner/repo> or --group <group_path> can be passed' arg:ret:64
        ___x_cmd_gl_param_init_owner_repo
        # shellcheck disable=2154
        url="/projects/${owner_repo}/issues"
    fi
    if [ -n "$group" ]; then
        local _avt_group="$group"
        ___x_cmd_gl____transform_avt_group || return
        url="/groups/$_avt_group/issues"
    fi

    if [ -n "$json" ] || [ -n "$ENFORCE_JSON" ]; then
        ___x_cmd_gl_get_multi "$url" state sort labels order_by milestone assignee_id assignee_username author_id author_username search confidential
    else
        ___x_cmd_gl_get_multi "$url" state sort labels order_by milestone assignee_id assignee_username author_id author_username search confidential | \
            x jo 2c             .id .iid           .project_id .state .title | \
            x csv header --add   ID  ISSUE_Nubmer   Project_ID  State  Title | \
            x csv static_tab
    fi
}
# EndSection

# Section: Create
# https://docs.gitlab.com/ee/api/issues.html#new-issue
___x_cmd_gl_issue_create(){
    param:scope     ___x_cmd_gl
    param:dsl       '
options:
   --repo|-r                                    "<owner_path>/<repo_path> or .id=<repo_id>"                                             <>
   --title                                      "The title of an issue"                                                                 <>

   --iid                                        "The internal ID of the project issue (requires administrator or project owner riglts)" <>=""
   --created_at                                 "When the issue was created."                                                           <>=""
   --issue_type                                 "The type of issue. One of issue, incident, or test_case. Default is issue."            <>="issue"  = issue incident test_case
   --due_date                                   "The due date."                                                                         <>=""
   --description                                "The description of an issue. Limited to 1,048,576 characters."                         <>=""
   --assignee_id                                "The ID of the user to assign the issue to. Only appears on GitLab Free."               <>:Number=""
   --assignee_ids                               "The IDs of the users to assign the issue to."                                          <>:array=""
   --discussion_to_resolve                      "The ID of a discussion to resolve"                                                     <>=""
   --epic_id                                    "ID of the epic to add the issue to. Valid values are greater than or equal to 0."      <>:Number=""
   --epic_iid                                   "IID of the epic to add the issue to. Valid values are greater than or equal to 0. "    <>:Number=""
   --labels                                     "Comma-separated label names for an issue"                                              <>=""
   --merge_request_to_resolve_discussions_of    "The IID of a merge request in which to resolve all issues"                             <>:Number=""
   --milestone_id                               "The global ID of a milestone to assign issue"                                          <>:Number=""
   --weight                                     "The weight of the issue. Valid values are greater than or equal to 0."                 <>:Number=""
   --confidential                               "Set an issue to be confidential. Default is false"                                     <>="false"  = true false
    --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/issues" "gen_gl_json" | _____x_cmd_gl_issue_ui_utils Creating
}
# EndSection

# Section: edit
# https://docs.gitlab.com/ee/api/issues.html#edit-issue
___x_cmd_gl_issue_edit(){
    param:scope     ___x_cmd_gl
    param:dsl       '
options:
   #1                   "The internal iid of a repo issue"                                                      <>
   --repo|-r            "<owner_path>/<repo_path> or .id=<repo_id>"                                             <>

   --add_labels         "Comma-separated label names to add to an issue."                                       <>=""
   --assignee_ids       "The IDs of the users to assign the issue to."                                          <>:array=""
   --description        "The description of an issue. Limited to 1,048,576 characters."                         <>=""
   --due_date           "The due date."                                                                         <>=""
   --epic_id            "ID of the epic to add the issue to. Valid values are greater than or equal to 0."      <>:Number=""
   --epic_iid           "IID of the epic to add the issue to. Valid values are greater than or equal to 0. "    <>:Number=""
   --issue_type         "The type of issue."                                                                    <>=""
   --labels             "Comma-separated label names for an issue"                                              <>=""
   --milestone_id       "The global ID of a milestone to assign the issue to."                                  <>:Number=""
   --remove_labels      "Comma-separated label names to remove from an issue. "                                 <>=""
   --state_event        "The state event of an issue. Set close to close the issue and reopen to reopen it "    <>=""  = close reopen
   --title              "The title of an issue "                                                                <>=""
   --updated_at         "When the issue was updated."                                                           <>=""
   --weight             "The weight of the issue. Valid values are greater than or equal to 0."                 <>:Number=""
   --confidential       "Updates an issue to be confidential"                                                   <>="false"  = true false
   --discussion_locked  "Flag indicating if the issue discussion is locked If the discussion is locked only project members can add or edit comments."

    --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/issues/$1" "gen_gl_json" | _____x_cmd_gl_issue_ui_utils Edit
}
# EndSection

# Section: rm
# https://docs.gitlab.com/ee/api/epic_issues.html#remove-an-issue-from-the-epic
___x_cmd_gl_issue_rm(){
    param:scope     ___x_cmd_gl
    param:dsl       '
options:
    #1              "The internal iid of a repo issue"                          <>
    --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 repo : $(___x_cmd_ui bold red "$owner_repo") ?" || return 0

    ___x_cmd_gl_curl del "/projects/$owner_repo/issues/$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 id $1 issue on $repo repo"
        else
            ___x_cmd_ui_tf false "Deleted id $1 issue on $repo repo failure:"
            ___x_cmd_gl____handle_resp
            return 1
        fi
    )
}
# EndSection

# Section: Reopen
# https://docs.gitlab.com/ee/api/issues.html#edit-issue
___x_cmd_gl_issue_reopen(){
    param:scope     ___x_cmd_github
    param:dsl       '
options:
    #1             "The internal iid of a repo issue"                   <>
    --repo|-r      "<owner_path>/<repo_path> or .id=<repo_id>"          <>
    --json|-j      "output raw JSON data"
'
    param:run

    local state_event=reopen

    ___x_cmd_gl_param_init_owner_repo
    ___x_cmd_gl_curl put "/projects/${owner_repo}/issues/${1}" -- state_event | _____x_cmd_gl_issue_ui_utils Reopen
}
# EndSection

# Section: Close
# https://docs.gitlab.com/ee/api/issues.html#list-merge-requests-that-close-a-particular-issue-on-merge
___x_cmd_gl_issue_close(){
     param:scope     ___x_cmd_github
    param:dsl       '
options:
    #1             "The internal iid of a repo issue"                   <>
    --repo|-r      "<owner_path>/<repo_path> or .id=<repo_id>"          <>
    --json|-j      "output raw JSON data"
'
    param:run

    local state_event=close

    ___x_cmd_gl_param_init_owner_repo
    ___x_cmd_gl_curl put "/projects/${owner_repo}/issues/${1}" -- state_event | _____x_cmd_gl_issue_ui_utils Close
}
# EndSection

# Section: issue utils
# https://docs.gitlab.com/ee/api/issues_statistics.html#get-issues-statistics
_____x_cmd_gl_issue_ui_utils(){
    if [ -n "$ENFORCE_JSON" ] || [ -n "$json" ]; then
        ___x_cmd_cmds_cat
        ___x_cmd_gl_http_error
        return
    fi
    (
        case "$1" in
            Creating|Edit|Reopen|Close)
                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
                _inf_msg="$1 issue successfully"
                _err_msg="$1 issue failure"
                ;;
        esac
        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