package chatrecords

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

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

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

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

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

func (l *GetChatRecordsListLogic) GetChatRecordsList(req *types.ChatRecordsListReq) (*types.ChatRecordsListResp, error) {
	var predicates []predicate.ChatRecords

	if req.SessionId == nil || *req.SessionId <= 0 {
		return nil, errorx.NewInvalidArgumentError("会话ID不能为空")
	}
	predicates = append(predicates, chatrecords.SessionID(*req.SessionId))
	if req.BotId != nil && *req.BotId > 0 {
		predicates = append(predicates, chatrecords.BotID(*req.BotId))
	}
	if req.BotType != nil && *req.BotType > 0 {
		predicates = append(predicates, chatrecords.BotType(*req.BotType))
	}

	data, err := l.svcCtx.DB.ChatRecords.Query().Where(predicates...).Order(ent.Asc("created_at")).Page(l.ctx, req.Page, req.PageSize)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	resp := &types.ChatRecordsListResp{}
	resp.Msg = errormsg.Success
	resp.Data.Total = data.PageDetails.Total

	for _, v := range data.List {
		roleType := ""
		if v.ContentType == 1 {
			roleType = "用户"
		} else if v.ContentType == 2 {
			roleType = "智能体"
		}
		resp.Data.Data = append(resp.Data.Data,
			types.ChatRecordsInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Content:     &v.Content,
				ContentType: &v.ContentType,
				RoleType:    &roleType,
				SessionId:   &v.SessionID,
				UserId:      &v.UserID,
				BotId:       &v.BotID,
				BotType:     &v.BotType,
			})
	}

	return resp, nil
}
