package chatsession

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

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

func (l *GetApiSessionListLogic) GetApiSessionList(req *types.ChatSessionListReq) (*types.ChatSessionListResp, error) {
	userId := l.ctx.Value("userId").(uint64)

	var predicates []predicate.ChatSession
	predicates = append(predicates, chatsession.UserID(userId))
	if req.BotType != nil && *req.BotType > 0 {
		predicates = append(predicates, chatsession.BotType(*req.BotType))
	} else {
		return nil, errorx.NewInvalidArgumentError("BotType cannot be null")
	}
	if req.BotId != nil && *req.BotId > 0 {
		predicates = append(predicates, chatsession.BotID(*req.BotId))
	} else {
		return nil, errorx.NewInvalidArgumentError("BotId cannot be null")
	}

	data, err := l.svcCtx.DB.ChatSession.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

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

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data,
			types.ChatSessionInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Name:    &v.Name,
				UserId:  &v.UserID,
				BotId:   &v.BotID,
				BotType: &v.BotType,
			})
	}

	return resp, nil
}
