package logic

import (
	"context"
	"errors"

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

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

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

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

func (l *RemoveParticipantLogic) RemoveParticipant(in *pb.RemoveParticipantReq) (*pb.RemoveParticipantResp, error) {
	store := l.svcCtx.Store
	store.Mu.Lock()
	defer store.Mu.Unlock()

	session, ok := store.Sessions[in.GetSessionId()]
	if !ok {
		return nil, errors.New("session not found")
	}

	filtered := make([]int64, 0, len(session.Participants))
	for _, p := range session.Participants {
		if p != in.GetUserId() {
			filtered = append(filtered, p)
		}
	}
	session.Participants = filtered
	session.UpdatedAt = nowUnix(0)

	return &pb.RemoveParticipantResp{}, nil
}
