package keyword

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

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

	"gorm.io/gorm"
)

type modifyKeywordMaterialRequest struct {
	Type            int32  `json:"type" binding:"required"`             // 素材类型(1:文本 2:图片)
	Content         string `json:"content" binding:"required"`          // 素材内容
	IntervalSeconds int32  `json:"interval_seconds" binding:"required"` // 发送间隔时间(单位:秒)
}

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

// ModifyKeywordMaterial 修改意图关键字素材
// @Summary 修改意图关键字素材
// @Description 修改意图关键字素材
// @Tags 管理端.意图关键字
// @Accept json
// @Produce json
// @Param id path string true "素材编号ID"
// @Param RequestBody body modifyKeywordMaterialRequest true "请求参数"
// @Success 200 {object} modifyKeywordMaterialResponse
// @Failure 400 {object} code.Failure
// @Router /api/admin/app/keyword/material/{id} [put]
// @Security LoginVerifyToken
func (h *handler) ModifyKeywordMaterial() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(modifyKeywordMaterialRequest)
		res := new(modifyKeywordMaterialResponse)
		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.AppKeywordReply.WithContext(ctx.RequestContext()).
			Where(h.readDB.AppKeywordReply.ID.Eq(int32(ID))).
			First()
		if err != nil && err != gorm.ErrRecordNotFound {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyKeywordMaterialError,
				fmt.Sprintf("%s: %s", code.Text(code.ModifyKeywordMaterialError), err.Error())),
			)
			return
		}

		if info == nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ModifyKeywordMaterialError,
				fmt.Sprintf("%s: 意图关键字素材编号(%d)不存在。", code.Text(code.ModifyKeywordMaterialError), ID)),
			)
			return
		}

		updateData := map[string]interface{}{
			"type":             req.Type,
			"content":          req.Content,
			"interval_seconds": req.IntervalSeconds,
			"updated_user":     ctx.SessionUserInfo().UserName,
			"updated_at":       time.Now(),
		}

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

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