// Package robot -----------------------------
// @file      : replyRuler.go
// @author    : JJXu
// @contact   : wavingbear@163.com
// @time      : 2025/6/13 17:39
// -------------------------------------------
package robot

import (
	"context"
	"fonchain-fiee/api/accountFiee"
	"fonchain-fiee/pkg/common/ws"
	"fonchain-fiee/pkg/service"
	"fonchain-fiee/pkg/service/asChat/consts"
	"fonchain-fiee/pkg/service/asChat/dto"
	"strings"
	"time"
)

type Reply struct {
	Response string
	Rules    []IRule
}

type IRule interface {
	Hit(msg *accountFiee.ChatRecordData) (hit bool, runTime time.Time, logic func(robotId int64, response string) error)
}

// KeywordsRuleChecker 关键字回复
type KeywordsRuleChecker struct {
	Keywords []string `json:"keywords"`
}

func (k KeywordsRuleChecker) Hit(record *accountFiee.ChatRecordData) (hit bool, runTime time.Time, logic func(robotId int64, response string) error) {
	for _, v := range k.Keywords {
		if strings.Contains(record.Content, v) {
			hit = true
			break
		}
	}
	logic = func(robotId int64, response string) error {
		var notice = dto.MessageListType{}
		notice.BuildMessage(record)
		_, err := consts.ChatRoom.SendSessionMessage(robotId, record.SessionId, ws.NewChatMsgType, notice)
		return err
	}
	return
}

// 用户打开聊天会话直接发送
type ReplyWhenUserJoinSession struct {
}

func (k ReplyWhenUserJoinSession) Hit(record *accountFiee.ChatRecordData, robotId int64) (hit bool, runTime time.Time, logic func(robotId int64, response string) error) {
	queryRes, err := service.AccountFieeProvider.GetChatRecordList(context.Background(), &accountFiee.GetChatRecordListRequest{
		Query: &accountFiee.ChatRecordData{
			SessionId: record.SessionId,
		},
		Page:     1,
		PageSize: 1,
		Order:    "created_at desc",
	})
	if err != nil {
		return
	}
	//如果最近一次的消息也是机器人发送的，就不再发送了
	for i, v := range queryRes.List {
		if i == 0 {
			if v.UserId == robotId {
				return
			} else {
				break
			}
		}
	}

	logic = func(robotId int64, response string) error {
		var notice = dto.MessageListType{}
		notice.BuildMessage(record)
		_, err = consts.ChatRoom.SendSessionMessage(robotId, record.SessionId, ws.NewChatMsgType, notice)
		return err
	}
	return
}
