package chatsession

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/errorx"
	"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 UpdateApiSessionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *UpdateApiSessionLogic) UpdateApiSession(req *types.ChatSessionInfo) (*types.BaseMsgResp, error) {
	userId := l.ctx.Value("userId").(uint64)
	var id uint64
	var name string

	if req.Id != nil && *req.Id > 0 {
		id = *req.Id
	}
	if req.Name != nil && *req.Name != "" {
		name = *req.Name
	}
	if id == 0 || name == "" {
		return nil, errorx.NewInvalidArgumentError("参数错误")
	}

	_, err := l.svcCtx.DB.ChatSession.Update().Where(chatsession.ID(id), chatsession.UserID(userId)).SetName(name).Save(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	return &types.BaseMsgResp{
		Code: 0,
		Msg:  errormsg.Success,
	}, nil
}
