// Copyright (c) 2026 Tigera, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package stream_test

import (
	"testing"

	googleproto "google.golang.org/protobuf/proto"

	"github.com/projectcalico/calico/goldmane/pkg/storage"
	"github.com/projectcalico/calico/goldmane/pkg/stream"
	"github.com/projectcalico/calico/goldmane/pkg/testutils"
	"github.com/projectcalico/calico/goldmane/pkg/types"
	"github.com/projectcalico/calico/goldmane/proto"
	"github.com/projectcalico/calico/lib/std/time"
)

// The stream goroutine reads DiachronicFlow windows while the aggregator goroutine keeps
// adding to the same flow. Run with -race.
func TestStreamReadRacesAddFlow(t *testing.T) {
	const now = 1000

	streams := stream.NewStreamManager()

	clk := func() time.Time { return time.Unix(now, 0) }
	ring := storage.NewBucketRing(20, 1, now, storage.WithStreamReceiver(streams), storage.WithNowFunc(clk))

	base := testutils.NewRandomFlow(now)
	addFlow := func(start int64) {
		fl, ok := googleproto.Clone(base).(*proto.Flow)
		if !ok {
			t.Fatal("cloned flow is not a *proto.Flow")
		}
		fl.StartTime = start
		fl.EndTime = start + 1
		ring.AddFlow(storage.FlowFromNode{Flow: types.ProtoToFlow(fl)})
	}
	for i := int64(1); i <= 5; i++ {
		addFlow(now - i)
	}

	flowStream := streams.Register(&proto.FlowStreamRequest{StartTimeGte: now - 5}, 100)
	if flowStream == nil {
		t.Fatal("nil stream")
	}
	defer flowStream.Close()

	ring.Backfill(streams, flowStream.ID(), flowStream.StartTimeGte())

	for range 50 {
		addFlow(now)
	}

	// Backfill stops before the bucket that is still filling, so the newest of the five flows is not sent.
	const wantBackfilled = 4

	var got int
	deadline := time.After(10 * time.Second)
	for got < wantBackfilled {
		select {
		case b := <-flowStream.Flows():
			if b.BuildInto(&proto.Filter{}, &proto.FlowResult{Flow: &proto.Flow{}}) {
				got++
			}
		case <-deadline:
			t.Fatalf("expected %d backfilled flows, got %d", wantBackfilled, got)
		}
	}

	select {
	case b := <-flowStream.Flows():
		if b.BuildInto(&proto.Filter{}, &proto.FlowResult{Flow: &proto.Flow{}}) {
			t.Errorf("expected only %d backfilled flows, got another", wantBackfilled)
		}
	case <-time.After(100 * time.Millisecond):
	}
}
