package message

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

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

	"gorm.io/gorm"
)

type userSendMessageRequest struct {
	AppID        string `json:"app_id" binding:"required"`         // 小程序ID
	FormUserID   string `json:"from_user_id" binding:"required"`   // 发送用户的ID
	FormUserName string `json:"from_user_name" binding:"required"` // 发送用户的昵称
	MsgType      int32  `json:"msg_type" binding:"required"`       // 消息类型(1:文本 2:图片)
	Content      string `json:"content" binding:"required"`        // 内容
}

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

// UserSendMessage 用户发送消息
// @Summary 用户发送消息
// @Description 用户发送消息
// @Tags 用户端
// @Accept json
// @Produce json
// @Param RequestBody body userSendMessageRequest true "请求参数"
// @Success 200 {object} userSendMessageResponse
// @Failure 400 {object} code.Failure
// @Router /api/app/send_message [post]
func (h *handler) UserSendMessage() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(userSendMessageRequest)
		res := new(userSendMessageResponse)
		if err := ctx.ShouldBindJSON(req); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.ParamBindError,
				validation.Error(err)),
			)
			return
		}

		createData := new(model.AppMessageLog)
		createData.AppID = req.AppID
		createData.SenderID = req.FormUserID
		createData.SenderName = req.FormUserName
		createData.Content = req.Content
		createData.ReceiverID = "888888"
		createData.MsgType = req.MsgType
		createData.SendTime = time.Now()
		createData.CreatedAt = time.Now()
		if err := h.writeDB.AppMessageLog.WithContext(ctx.RequestContext()).Create(createData); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusBadRequest,
				code.SendMessageError,
				fmt.Sprintf("%s: %s", code.Text(code.SendMessageError), err.Error()),
			))
		}

		time.AfterFunc(1*time.Second, func() {
			if req.MsgType == 1 { // 自动回复逻辑
				textMsg := new(services.TextMessage)
				if err := json.Unmarshal([]byte(req.Content), &textMsg); err != nil {
					h.logger.Error(fmt.Sprintf("AppID(%s),用户ID(%s),发送内容(%s) JSON解析失败: %s", req.AppID, req.FormUserID, req.Content, err.Error()))
					return
				}

				keyword, err := h.readDB.AppKeyword.
					Where(h.readDB.AppKeyword.AppID.Eq(req.AppID)).
					Where(h.readDB.AppKeyword.Keyword.Eq(textMsg.Message)).
					Order(h.readDB.AppKeyword.ID.Asc()).
					First()
				if err != nil && err != gorm.ErrRecordNotFound {
					h.logger.Error(fmt.Sprintf("AppID(%s),用户ID(%s),发送内容(%s) 获取意图关键字失败: %s", req.AppID, req.FormUserID, req.Content, err.Error()))
					return
				}

				if keyword == nil {
					return
				}

				// 获取群组关键字回复信息
				reply, err := h.readDB.AppKeywordReply.
					Where(h.readDB.AppKeywordReply.AppID.Eq(req.AppID)).
					Where(h.readDB.AppKeywordReply.KeywordID.Eq(keyword.ID)).
					Find()
				if err != nil && err != gorm.ErrRecordNotFound {
					h.logger.Error(fmt.Sprintf("AppID(%s),用户ID(%s),发送内容(%s) 获取群组关键字回复失败: %s", req.AppID, req.FormUserID, req.Content, err.Error()))
					return
				}

				if len(reply) == 0 {
					return
				}

				for _, v := range reply {
					time.Sleep(time.Duration(v.IntervalSeconds) * time.Second)

					replyData := new(model.AppMessageLog)
					replyData.AppID = req.AppID
					replyData.SenderID = "888888"
					replyData.SenderName = "平台"
					replyData.Content = v.Content
					replyData.ReceiverID = req.FormUserID
					replyData.MsgType = v.Type
					replyData.SendTime = time.Now()
					replyData.CreatedAt = time.Now()
					if err := h.writeDB.AppMessageLog.Create(replyData); err != nil {
						h.logger.Error(fmt.Sprintf("AppID(%s),用户ID(%s),发送内容(%s) 回复关键字回复失败: %s", req.AppID, req.FormUserID, req.Content, err.Error()))
					}
				}
			}
		})

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