package chatrecords

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent"
	"wechat-api/ent/chatrecords"
	"wechat-api/ent/chatsession"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetApiRecommendChatLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetApiRecommendChatLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetApiRecommendChatLogic {
	return &GetApiRecommendChatLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *GetApiRecommendChatLogic) GetApiRecommendChat(req *types.ChatRecommendReq) (*types.ChatRecommendResp, error) {
	recommendCount := 5

	if req.SessionId != nil && *req.SessionId > 0 {
		userId := l.ctx.Value("userId").(uint64)

		_, err := l.svcCtx.DB.ChatSession.Query().Where(
			chatsession.UserID(userId),
			chatsession.ID(*req.SessionId),
		).Only(l.ctx)
		if err != nil {
			if ent.IsNotFound(err) {
				return nil, errorx.NewInvalidArgumentError("sessionId not found")
			}
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}

		resp := types.ChatRecommendResp{}
		resp.BaseDataInfo.Code = 0
		resp.BaseDataInfo.Msg = errormsg.Success

		list, err := l.svcCtx.DB.ChatRecords.Query().Where(chatrecords.SessionID(*req.SessionId)).Limit(recommendCount).All(l.ctx)
		if err != nil {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}

		questionList := make([]string, 0, recommendCount)
		recommendList := make([]string, 0, recommendCount)
		for _, val := range list {
			questionList = append(questionList, val.Content)
		}

		//TODO 这里根据历史记录返回推荐内容

		resp.Data.SessionId = *req.SessionId
		resp.Data.Data = recommendList

		return &resp, nil
	} else {
		return nil, errorx.NewInvalidArgumentError("sessionId cannot be null")
	}
}
