package jellyfin

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

func TestRefreshLibraries_OK(t *testing.T) {
	var gotPath, gotToken, gotMethod string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		gotMethod = r.Method
		gotPath = r.URL.Path
		gotToken = r.Header.Get("X-Emby-Token")
		w.WriteHeader(http.StatusNoContent)
	}))
	defer srv.Close()

	c, err := New(Config{URL: srv.URL, APIKey: "secret"}, nil)
	if err != nil {
		t.Fatalf("New: %v", err)
	}
	if err := c.RefreshLibraries(context.Background()); err != nil {
		t.Fatalf("RefreshLibraries: %v", err)
	}
	if gotMethod != http.MethodPost {
		t.Errorf("method = %q, want POST", gotMethod)
	}
	if gotPath != "/Library/Refresh" {
		t.Errorf("path = %q, want /Library/Refresh", gotPath)
	}
	if gotToken != "secret" {
		t.Errorf("token = %q, want secret", gotToken)
	}
}

func TestRefreshLibraries_TrimsTrailingSlash(t *testing.T) {
	var gotPath string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		gotPath = r.URL.Path
		w.WriteHeader(http.StatusNoContent)
	}))
	defer srv.Close()

	c, err := New(Config{URL: srv.URL + "/", APIKey: "k"}, nil)
	if err != nil {
		t.Fatalf("New: %v", err)
	}
	if err := c.RefreshLibraries(context.Background()); err != nil {
		t.Fatalf("RefreshLibraries: %v", err)
	}
	if gotPath != "/Library/Refresh" {
		t.Errorf("path = %q, want /Library/Refresh (без двойного слеша)", gotPath)
	}
}

func TestRefreshLibraries_ErrorStatus(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusUnauthorized)
	}))
	defer srv.Close()

	c, err := New(Config{URL: srv.URL, APIKey: "bad"}, nil)
	if err != nil {
		t.Fatalf("New: %v", err)
	}
	if err := c.RefreshLibraries(context.Background()); err == nil {
		t.Fatal("ожидали ошибку на 401, получили nil")
	}
}
