package aoiprxkit

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

type nopCloser struct{ io.Reader }

func (n nopCloser) Close() error { return nil }

func TestStreamReceiverPCM(t *testing.T) {
	var buf bytes.Buffer
	samples := []int32{100, -100, 200, -200}
	if err := WritePCM32Packet(&buf, 2, 48000, 2, 55, 999, samples); err != nil {
		t.Fatalf("unexpected write error: %v", err)
	}

	got := make(chan PCMFrame, 1)
	rx, err := NewStreamReceiver(StreamReceiverConfig{SourceLabel: "test-source"}, func(ctx context.Context) (io.ReadCloser, error) {
		_ = ctx
		return nopCloser{Reader: bytes.NewReader(buf.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 frame.SampleRateHz != 48000 || frame.Channels != 2 || frame.Source != "test-source" {
			t.Fatalf("unexpected frame meta: %+v", frame)
		}
		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")
	}
}
