package api

import (
	"testing"

	"github.com/ponzischeme89/memby/server/internal/sonarr"
	"github.com/ponzischeme89/memby/server/internal/store"
)

func TestMatchSonarrSeriesUsesNormalizedTitleAndYear(t *testing.T) {
	year := 2026
	all := []sonarr.Series{
		{ID: 1, Title: "The Other Show", Year: 2026},
		{ID: 2, Title: "Northbound: NZ", Year: 2026},
	}
	got := matchSonarrSeries(store.UserShow{Title: "Northbound - NZ", Year: &year}, all)
	if got == nil || got.ID != 2 {
		t.Fatalf("match = %+v, want series 2", got)
	}
}

func TestSeriesLifecycleUsesViewerFacingStates(t *testing.T) {
	tests := map[string]string{
		"continuing": "Continuing",
		"upcoming":   "Continuing",
		"ended":      "Cancelled",
		"deleted":    "Cancelled",
		"":           "Unknown",
	}
	for input, want := range tests {
		if got := seriesLifecycle(input); got != want {
			t.Errorf("seriesLifecycle(%q) = %q, want %q", input, got, want)
		}
	}
}

func TestContinuingSonarrStatus(t *testing.T) {
	for _, status := range []string{"continuing", "Continuing", "upcoming"} {
		if !isContinuingSonarrStatus(status) {
			t.Errorf("%q should auto-follow", status)
		}
	}
	for _, status := range []string{"ended", "deleted", ""} {
		if isContinuingSonarrStatus(status) {
			t.Errorf("%q should not auto-follow", status)
		}
	}
}

func TestAutoFollowStartsHalfwayThroughEpisode(t *testing.T) {
	if shouldAutoFollowShow("started", 900, 1_000) {
		t.Fatal("starting or resuming playback must not auto-follow")
	}
	if shouldAutoFollowShow("progress", 499, 1_000) {
		t.Fatal("less than half an episode must not auto-follow")
	}
	if !shouldAutoFollowShow("progress", 500, 1_000) {
		t.Fatal("half an episode should auto-follow")
	}
	if shouldAutoFollowShow("progress", 500, 0) {
		t.Fatal("unknown durations must not auto-follow")
	}
}
