package mp3

import (
	"bytes"
	"context"
	"errors"
	"os"
	"path/filepath"
	"testing"

	"github.com/jan/fm-rds-tx/internal/ingest"
	"github.com/jan/fm-rds-tx/internal/ingest/decoder"
)

func TestDecodeStream(t *testing.T) {
	tonePath := filepath.Join("testdata", "tone_44k_stereo.mp3")
	data, err := os.ReadFile(tonePath)
	if err != nil {
		t.Fatalf("read fixture: %v", err)
	}

	var chunks []ingest.PCMChunk
	d := New()
	err = d.DecodeStream(context.Background(), bytes.NewReader(data), decoder.StreamMeta{
		ContentType: "audio/mpeg",
		SourceID:    "mp3-test",
	}, func(c ingest.PCMChunk) error {
		chunks = append(chunks, c)
		return nil
	})
	if err != nil {
		t.Fatalf("decode: %v", err)
	}
	if len(chunks) == 0 {
		t.Fatal("expected chunks")
	}
	if chunks[0].Channels != 2 {
		t.Fatalf("channels=%d want 2", chunks[0].Channels)
	}
	if chunks[0].SampleRateHz != 44100 {
		t.Fatalf("sampleRate=%d want 44100", chunks[0].SampleRateHz)
	}
	if len(chunks[0].Samples) == 0 {
		t.Fatal("expected samples in first chunk")
	}
}

func TestDecodeStreamNilReader(t *testing.T) {
	err := New().DecodeStream(context.Background(), nil, decoder.StreamMeta{}, func(ingest.PCMChunk) error { return nil })
	if !errors.Is(err, decoder.ErrUnsupported) {
		t.Fatalf("expected unsupported, got %v", err)
	}
}

func TestDecodeStreamNilEmit(t *testing.T) {
	err := New().DecodeStream(context.Background(), bytes.NewReader([]byte("not-mp3")), decoder.StreamMeta{}, nil)
	if !errors.Is(err, decoder.ErrUnsupported) {
		t.Fatalf("expected unsupported, got %v", err)
	}
}
