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/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 GetApiChatListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GetApiChatListLogic) GetApiChatList(req *types.ChatRecordsListReq) (*types.ChatRecordsListResp, error) {
	userId := l.ctx.Value("userId").(uint64)

	var predicates []predicate.ChatRecords
	predicates = append(predicates, chatrecords.UserID(userId))

	var sessionId uint64
	if req.SessionId != nil && *req.SessionId > 0 {
		sessionId = *req.SessionId
	}
	if sessionId == 0 {
		return nil, errorx.NewInvalidArgumentError("会话ID不能为空")
	}
	predicates = append(predicates, chatrecords.SessionID(sessionId))
	if req.BotId != nil && *req.BotId > 0 {
		predicates = append(predicates, chatrecords.BotID(*req.BotId))
	} else {
		return nil, errorx.NewInvalidArgumentError("BotId参数错误")
	}
	if req.BotType != nil && *req.BotType > 0 {
		predicates = append(predicates, chatrecords.BotType(*req.BotType))
	} else {
		return nil, errorx.NewInvalidArgumentError("BotType参数错误")
	}

	data, err := l.svcCtx.DB.ChatRecords.Query().Where(predicates...).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 {
		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,
				SessionId:   &v.SessionID,
				UserId:      &v.UserID,
				BotId:       &v.BotID,
				BotType:     &v.BotType,
			})
	}

	return resp, nil
}
