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

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

func (l *AddParticipantLogic) AddParticipant(in *pb.AddParticipantReq) (*pb.AddParticipantResp, 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")
	}

	for _, p := range session.Participants {
		if p == in.GetUserId() {
			return &pb.AddParticipantResp{}, nil
		}
	}
	session.Participants = append(session.Participants, in.GetUserId())
	session.UpdatedAt = nowUnix(0)

	return &pb.AddParticipantResp{}, nil
}
