package admin

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

	"mini-chat/internal/code"
	"mini-chat/internal/pkg/core"
	"mini-chat/internal/pkg/utils"
	"mini-chat/internal/pkg/validation"

	"gorm.io/gorm"
)

type modifyAdminRequest struct {
	UserName string `json:"username" binding:"required"` // 用户名
	NickName string `json:"nickname" binding:"required"` // 昵称
	Mobile   string `json:"mobile"`                      // 手机号
	Password string `json:"password" binding:"required"` // 密码
	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 == "" && req.Password == "" {
			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
		}

		checkIdInfo, err := h.readDB.Admin.WithContext(ctx.RequestContext()).
			Where(h.readDB.Admin.ID.Eq(int32(id))).
			First()
		if err != nil && err != gorm.ErrRecordNotFound {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyAdminError,
				fmt.Sprintf("%s: %s", code.Text(code.ModifyAdminError), err.Error())),
			)
			return
		}

		if checkIdInfo == nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyAdminError,
				fmt.Sprintf("%s: %s", code.Text(code.ModifyAdminError), "该账号不存在")),
			)
			return
		}

		checkUserNameInfo, err := h.readDB.Admin.WithContext(ctx.RequestContext()).
			Where(h.readDB.Admin.ID.Neq(int32(id))).
			Where(h.readDB.Admin.Username.Eq(req.UserName)).
			First()
		if err != nil && err != gorm.ErrRecordNotFound {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyAdminError,
				fmt.Sprintf("%s: %s", code.Text(code.ModifyAdminError), err.Error())),
			)
			return
		}

		if checkUserNameInfo != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyAdminError,
				fmt.Sprintf("%s: %s", code.Text(code.ModifyAdminError), "该账号已存在")),
			)
			return
		}

		hashedPassword, err := utils.GenerateAdminHashedPassword(req.Password)
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyAdminError,
				fmt.Sprintf("%s: %s", code.Text(code.ModifyAdminError), err.Error())),
			)
			return
		}

		checkIdInfo.Username = req.UserName
		checkIdInfo.Nickname = req.NickName
		checkIdInfo.Mobile = req.Mobile
		checkIdInfo.Password = hashedPassword
		checkIdInfo.Avatar = req.Avatar
		checkIdInfo.UpdatedUser = ctx.SessionUserInfo().UserName
		checkIdInfo.UpdatedAt = time.Now()
		if err := h.writeDB.Admin.WithContext(ctx.RequestContext()).Save(checkIdInfo); 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)
	}
}
