package admin

import (
	"fmt"
	"net/http"
	"strconv"

	"bindbox-game/internal/code"
	"bindbox-game/internal/pkg/core"
	"bindbox-game/internal/pkg/validation"
	adminsvc "bindbox-game/internal/service/admin"
)

type modifyAdminRequest struct {
	UserName string `json:"username" binding:"required"` // 用户名
	NickName string `json:"nickname" binding:"required"` // 昵称
	Mobile   string `json:"mobile"`                      // 手机号
	Password string `json:"password"`                    // 密码
	Avatar   string `json:"avatar"`                      // 头像
}

type modifyAdminResponse struct {
	Message string `json:"message"` // 提示信息
}

// ModifyAdmin 编辑客服
// @Summary 编辑客服
// @Description 编辑客服
// @Tags 管理端.客服管理
// @Accept json
// @Produce json
// @Param id path string true "编号ID"
// @Param RequestBody body modifyAdminRequest true "请求参数"
// @Success 200 {object} modifyAdminResponse
// @Failure 400 {object} code.Failure
// @Router /api/admin/{id} [put]
// @Security LoginVerifyToken
func (h *handler) ModifyAdmin() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(modifyAdminRequest)
		res := new(modifyAdminResponse)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				validation.Error(err)),
			)
			return
		}

		if ctx.SessionUserInfo().IsSuper != 1 {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyAdminError,
				fmt.Sprintf("%s: %s", code.Text(code.ModifyAdminError), "禁止操作")),
			)
			return
		}

		if req.UserName == "" && req.NickName == "" {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				"用户名、昵称为必填"),
			)
			return
		}

		id, err := strconv.Atoi(ctx.Param("id"))
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				"未传递编号ID"),
			)
			return
		}

		if err := h.svc.Modify(ctx.RequestContext(), id, adminsvc.ModifyInput{
			Username:  req.UserName,
			Nickname:  req.NickName,
			Mobile:    req.Mobile,
			Password:  req.Password,
			Avatar:    req.Avatar,
			UpdatedBy: ctx.SessionUserInfo().UserName,
		}); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyAdminError,
				fmt.Sprintf("%s: %s", code.Text(code.ModifyAdminError), err.Error())),
			)
			return
		}

		res.Message = "操作成功"
		ctx.Payload(res)
	}
}
