package api

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

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

func TestSubtitleFixAvailableNeedsAUsableReference(t *testing.T) {
	server := &Server{store: &store.Store{}}
	english := playableSubtitle{ID: "1", Language: "eng", URL: "https://emby/subtitle/1.srt"}
	italian := playableSubtitle{ID: "2", Language: "ita", URL: "https://emby/subtitle/2.srt"}

	if server.subtitleFixAvailable([]playableSubtitle{english}) {
		t.Fatal("one subtitle cannot be checked against itself")
	}
	if !server.subtitleFixAvailable([]playableSubtitle{english, italian}) {
		t.Fatal("two readable text tracks should make timing repair available")
	}
	if (&Server{}).subtitleFixAvailable([]playableSubtitle{english, italian}) {
		t.Fatal("a gateway with no store cannot keep the repaired copy")
	}
}

func TestSubtitleFixHandlerRejectsAnUnnamedTrack(t *testing.T) {
	server := &Server{store: &store.Store{}}
	request := httptest.NewRequest(
		http.MethodPost,
		"/v1/items/42/subtitles/fix",
		strings.NewReader(`{"subtitleId":"  "}`),
	)
	request.SetPathValue("id", "42")
	recorder := httptest.NewRecorder()

	server.handleSubtitleFix(recorder, request, store.Session{})

	if recorder.Code != http.StatusBadRequest {
		t.Fatalf("status = %d, want 400", recorder.Code)
	}
	if !strings.Contains(recorder.Body.String(), "no subtitle was named") {
		t.Fatalf("body = %q", recorder.Body.String())
	}
}
