package keyword

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

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

	"gorm.io/gorm"
)

type modifyKeywordRequest struct {
	Keyword string `json:"keyword" binding:"required"` // 意图关键字
}

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

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

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

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

		if info == nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyKeywordError,
				fmt.Sprintf("%s: 编号(%d)不存在。", code.Text(code.ModifyKeywordError), ID)),
			)
			return
		}

		req.Keyword = strings.TrimSpace(req.Keyword)

		if info.Keyword != req.Keyword {
			// 验证关键字是否已存在
			if _, err := h.readDB.AppKeyword.WithContext(ctx.RequestContext()).
				Where(h.readDB.AppKeyword.AppID.Eq(info.AppID)).
				Where(h.readDB.AppKeyword.Keyword.Eq(req.Keyword)).
				First(); err == nil {
				ctx.AbortWithError(core.Error(
					http.StatusBadRequest,
					code.ModifyKeywordError,
					fmt.Sprintf("%s: 该关键字(%s)已存在", code.Text(code.ModifyKeywordError), req.Keyword)),
				)
				return
			}
		}

		updateData := map[string]interface{}{
			"keyword":      req.Keyword,
			"updated_user": ctx.SessionUserInfo().UserName,
			"updated_at":   time.Now(),
		}

		if _, err := h.writeDB.AppKeyword.WithContext(ctx.RequestContext()).
			Where(h.writeDB.AppKeyword.ID.Eq(int32(ID))).
			Updates(updateData); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyKeywordError,
				fmt.Sprintf("%s: %s", code.Text(code.ModifyKeywordError), err.Error())),
			)
		}

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