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

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

func (l *AddChatSessionsLogic) AddChatSessions(in *pb.AddChatSessionsReq) (*pb.AddChatSessionsResp, error) {
	if in.GetType() == "" {
		return nil, errors.New("type is required")
	}
	if in.GetCreatorId() <= 0 {
		return nil, errors.New("creatorId is required")
	}

	store := l.svcCtx.Store
	store.Mu.Lock()
	defer store.Mu.Unlock()

	now := nowUnix(0)
	participants := append([]int64(nil), in.GetParticipants()...)
	hasCreator := false
	for _, p := range participants {
		if p == in.GetCreatorId() {
			hasCreator = true
			break
		}
	}
	if !hasCreator {
		participants = append(participants, in.GetCreatorId())
	}

	session := &pb.ChatSessions{
		Id:           store.NextSession(),
		Type:         in.GetType(),
		Name:         in.GetName(),
		CreatorId:    in.GetCreatorId(),
		Participants: participants,
		CreatedAt:    now,
		UpdatedAt:    now,
	}
	store.Sessions[session.Id] = session

	return &pb.AddChatSessionsResp{Id: session.Id}, nil
}
