package logic

import (
	"context"

	"juwan-backend/app/chat/rpc/internal/svc"
	"juwan-backend/app/chat/rpc/pb"

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

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

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

func (l *DelChatMessagesLogic) DelChatMessages(in *pb.DelChatMessagesReq) (*pb.DelChatMessagesResp, error) {
	store := l.svcCtx.Store
	store.Mu.Lock()
	defer store.Mu.Unlock()

	msg, ok := store.Messages[in.GetId()]
	if ok {
		ids := store.SessionMessages[msg.SessionId]
		filtered := make([]int64, 0, len(ids))
		for _, id := range ids {
			if id != in.GetId() {
				filtered = append(filtered, id)
			}
		}
		store.SessionMessages[msg.SessionId] = filtered
	}
	delete(store.Messages, in.GetId())

	return &pb.DelChatMessagesResp{}, nil
}
