package mdblist

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"
)

func TestMovieReadsAllAvailableNumericRatings(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/tmdb/movie/278/" || r.URL.Query().Get("apikey") != "secret" {
			t.Fatalf("unexpected request %s?%s", r.URL.Path, r.URL.RawQuery)
		}
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"ratings":[
			{"source":"imdb","value":9.3,"score":93},
			{"source":"letterboxd","value":"4.6"},
			{"source":"metacritic","value":null},
			{"source":"tomatoes","value":"not available"}
		]}`))
	}))
	defer server.Close()

	got, err := New(server.URL, time.Second).Movie(context.Background(), "secret", "tmdb", "278")
	if err != nil {
		t.Fatal(err)
	}
	if len(got) != 2 || got[0].Source != "imdb" || got[0].Value != 9.3 ||
		got[1].Source != "letterboxd" || got[1].Value != 4.6 {
		t.Fatalf("ratings = %+v", got)
	}
}

func TestMovieRejectsUnsupportedProviderBeforeCallingUpstream(t *testing.T) {
	_, err := New("https://example.invalid", time.Second).
		Movie(context.Background(), "secret", "tvdb", "42")
	if err == nil {
		t.Fatal("expected unsupported provider to fail")
	}
}

func TestMediaUsesShowEndpointForSeries(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/imdb/show/tt0944947/" {
			t.Fatalf("unexpected path %s", r.URL.Path)
		}
		_, _ = w.Write([]byte(`{"ratings":[{"source":"trakt","value":89}]}`))
	}))
	defer server.Close()
	got, err := New(server.URL, time.Second).Media(context.Background(), "secret", "imdb", "tt0944947", "series")
	if err != nil || len(got) != 1 || got[0].Value != 89 {
		t.Fatalf("ratings=%+v err=%v", got, err)
	}
}
