package admin

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

	"mini-chat/internal/code"
	"mini-chat/internal/pkg/core"
	"mini-chat/internal/pkg/utils"
	"mini-chat/internal/pkg/validation"
	"mini-chat/internal/repository/mysql/model"

	"gorm.io/gorm"
)

type createAdminRequest 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 createAdminResponse struct {
	Message string `json:"message"` // 提示信息
}

// CreateAdmin 新增客服
// @Summary 新增客服
// @Description 新增客服
// @Tags 管理端.客服管理
// @Accept json
// @Produce json
// @Param RequestBody body createAdminRequest true "请求参数"
// @Success 200 {object} createAdminResponse
// @Failure 400 {object} code.Failure
// @Router /api/admin/create [post]
// @Security LoginVerifyToken
func (h *handler) CreateAdmin() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(createAdminRequest)
		res := new(createAdminResponse)
		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.CreateAdminError,
				fmt.Sprintf("%s: %s", code.Text(code.CreateAdminError), "禁止操作")),
			)
			return
		}

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

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

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

		Admin := new(model.Admin)
		Admin.Username = req.UserName
		Admin.Nickname = req.NickName
		Admin.Mobile = req.Mobile
		Admin.Password = hashedPassword
		Admin.Avatar = req.Avatar
		Admin.LoginStatus = 1
		Admin.IsSuper = 0
		Admin.CreatedUser = ctx.SessionUserInfo().UserName
		Admin.CreatedAt = time.Now()
		if err := h.writeDB.Admin.WithContext(ctx.RequestContext()).Create(Admin); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.CreateAdminError,
				fmt.Sprintf("%s: %s", code.Text(code.CreateAdminError), err.Error())),
			)
			return
		}

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