package metadata

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

func newTVMaze(t *testing.T, url string) *TVMaze {
	t.Helper()
	c, err := NewTVMaze(TVMazeConfig{BaseURL: url}, nil)
	if err != nil {
		t.Fatalf("NewTVMaze: %v", err)
	}
	return c
}

func TestTVMaze_SearchSeries(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/search/shows" || r.URL.Query().Get("q") != "Fargo" {
			t.Errorf("request = %s?%s", r.URL.Path, r.URL.RawQuery)
		}
		_, _ = w.Write([]byte(`[
			{"score":0.9,"show":{"id":1,"name":"Fargo","premiered":"2014-04-15",
			 "externals":{"thetvdb":269613,"imdb":"tt2802850"}}},
			{"score":0.1,"show":{"id":2,"name":"Other","premiered":"2010-01-01",
			 "externals":{"thetvdb":0,"imdb":"tt999"}}}
		]`))
	}))
	defer srv.Close()

	got, err := newTVMaze(t, srv.URL).Search(context.Background(), Query{Type: Series, Title: "Fargo", Year: 2014})
	if err != nil {
		t.Fatalf("Search: %v", err)
	}
	if len(got) != 2 {
		t.Fatalf("got %d candidates", len(got))
	}
	c := got[0]
	if c.Provider != "tvmaze" || c.ID != "1" || c.Title != "Fargo" || c.Year != 2014 {
		t.Errorf("candidate = %+v", c)
	}
	if c.URL != "https://www.tvmaze.com/shows/1" {
		t.Errorf("URL = %q", c.URL)
	}
	// TVDB-id из externals → тег папки.
	if c.TagProvider != "tvdb" || c.TagID != "269613" {
		t.Errorf("tag = %s/%s, want tvdb/269613", c.TagProvider, c.TagID)
	}
	// Без thetvdb → фолбэк на imdb.
	if got[1].TagProvider != "imdb" || got[1].TagID != "tt999" {
		t.Errorf("fallback tag = %s/%s", got[1].TagProvider, got[1].TagID)
	}
}

func TestTVMaze_SearchMovieEmpty(t *testing.T) {
	// Для фильмов TVMaze не вызывается вовсе.
	srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
		t.Error("movie search must not hit the network")
	}))
	defer srv.Close()

	got, err := newTVMaze(t, srv.URL).Search(context.Background(), Query{Type: Movie, Title: "X"})
	if err != nil || got != nil {
		t.Errorf("movie search = %v, %v; want nil, nil", got, err)
	}
}

func TestTVMaze_SeasonEpisodeCounts(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/shows/1/episodes" {
			t.Errorf("path = %q", r.URL.Path)
		}
		_, _ = w.Write([]byte(`[
			{"season":1,"number":1},{"season":1,"number":2},
			{"season":2,"number":1}
		]`))
	}))
	defer srv.Close()

	counts, err := newTVMaze(t, srv.URL).SeasonEpisodeCounts(context.Background(), "1")
	if err != nil {
		t.Fatalf("SeasonEpisodeCounts: %v", err)
	}
	if counts[1] != 2 || counts[2] != 1 {
		t.Errorf("counts = %v", counts)
	}
}
