package aoiprxkit

import (
	"bytes"
	"context"
	"io"
	"testing"
	"time"
)

type readCloser struct{ io.Reader }

func (r readCloser) Close() error { return nil }

func TestSRTReceiverWithCustomOpener(t *testing.T) {
	var stream bytes.Buffer
	samples := []int32{1, 2, 3, 4}
	if err := WritePCM32Packet(&stream, 2, 48000, 2, 1, 480, samples); err != nil {
		t.Fatalf("unexpected write error: %v", err)
	}

	got := make(chan PCMFrame, 1)
	rx, err := NewSRTReceiverWithOpener(SRTConfig{
		URL:          "srt://example:9000?mode=listener",
		SampleRateHz: 48000,
		Channels:     2,
	}, func(ctx context.Context, cfg SRTConfig) (io.ReadCloser, error) {
		_ = ctx
		_ = cfg
		return readCloser{Reader: bytes.NewReader(stream.Bytes())}, nil
	}, func(frame PCMFrame) {
		select {
		case got <- frame:
		default:
		}
	})
	if err != nil {
		t.Fatalf("unexpected constructor error: %v", err)
	}
	if err := rx.Start(context.Background()); err != nil {
		t.Fatalf("unexpected start error: %v", err)
	}
	defer rx.Stop()

	select {
	case frame := <-got:
		if len(frame.Samples) != len(samples) {
			t.Fatalf("unexpected sample len: %d", len(frame.Samples))
		}
		for i := range samples {
			if frame.Samples[i] != samples[i] {
				t.Fatalf("sample %d mismatch: got=%d want=%d", i, frame.Samples[i], samples[i])
			}
		}
	case <-time.After(500 * time.Millisecond):
		t.Fatalf("timeout waiting for frame")
	}
}
