package services

import (
	"sync"
	"testing"
)

func TestSimulationSubscriptionsCoalesceWithoutLosingEvents(t *testing.T) {
	s := NewSimulationLogStore(t.TempDir())
	id := NewSimulationID()
	updates, cancel, err := s.Subscribe(1, id)
	if err != nil {
		t.Fatal(err)
	}
	foreign, stopForeign, err := s.Subscribe(2, id)
	if err != nil {
		t.Fatal(err)
	}
	r, err := s.Start(1, id, NewSimulationID(), nil)
	if err != nil {
		t.Fatal(err)
	}
	var wg sync.WaitGroup
	for i := 0; i < 12; i++ {
		wg.Add(1)
		go func() { defer wg.Done(); r.Record("tool_completed", "check_answer", "completed", nil) }()
	}
	wg.Wait()
	r.Finish("completed", nil)
	select {
	case <-updates:
	default:
		t.Fatal("subscriber was not notified")
	}
	select {
	case <-foreign:
		t.Fatal("another agent was notified")
	default:
	}
	log, err := s.Read(1, id)
	if err != nil || len(log.Events) != 14 || log.Status != "completed" {
		t.Fatalf("coalescing lost events: %+v %v", log, err)
	}
	cancel()
	cancel()
	stopForeign()
	if len(s.subscribers) != 0 {
		t.Fatal("subscription leaked after cancellation")
	}
	if _, _, err := s.Subscribe(1, "../secret"); err == nil {
		t.Fatal("invalid subscription ID allowed")
	}
}
