package decoder

import (
	"context"
	"errors"
	"io"
	"testing"

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

type fakeDecoder struct{ name string }

func (d *fakeDecoder) Name() string { return d.name }

func (d *fakeDecoder) DecodeStream(_ context.Context, _ io.Reader, _ StreamMeta, _ func(ingest.PCMChunk) error) error {
	return nil
}

func TestRegistrySelectByContentType(t *testing.T) {
	r := NewRegistry()
	r.Register("mp3", func() Decoder { return &fakeDecoder{name: "mp3"} })
	r.Register("oggvorbis", func() Decoder { return &fakeDecoder{name: "ogg"} })
	r.Register("aac", func() Decoder { return &fakeDecoder{name: "aac"} })

	tests := []struct {
		ct   string
		want string
	}{
		{"audio/mpeg", "mp3"},
		{"audio/mpeg; charset=utf-8", "mp3"},
		{"application/ogg", "ogg"},
		{"audio/ogg;codecs=vorbis", "ogg"},
		{"audio/aac", "aac"},
		{"audio/aacp", "aac"},
	}
	for _, tt := range tests {
		dec, err := r.SelectByContentType(tt.ct)
		if err != nil {
			t.Fatalf("content-type %s: %v", tt.ct, err)
		}
		if dec.Name() != tt.want {
			t.Fatalf("content-type %s: got %s want %s", tt.ct, dec.Name(), tt.want)
		}
	}
}

func TestRegistrySelectByContentTypeUnsupported(t *testing.T) {
	r := NewRegistry()
	_, err := r.SelectByContentType("application/octet-stream")
	if !errors.Is(err, ErrUnsupported) {
		t.Fatalf("expected ErrUnsupported, got %v", err)
	}
}
