package api

import (
	"testing"

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

func TestSubtitleMIME(t *testing.T) {
	tests := map[string]string{
		"srt":      "application/x-subrip",
		"subrip":   "application/x-subrip",
		"webvtt":   "text/vtt",
		"ass":      "text/x-ssa",
		"mov_text": "application/x-quicktime-tx3g",
		"pgssub":   "",
	}
	for codec, want := range tests {
		if got := subtitleMIME(codec, ""); got != want {
			t.Errorf("subtitleMIME(%q) = %q, want %q", codec, got, want)
		}
	}
}

func TestSelectPlaybackDeliveryUsesNegotiatedDirectStream(t *testing.T) {
	source := emby.MediaSourceInfo{
		SupportsDirectStream: true,
		DirectStreamURL:      "/Videos/item/stream.mp4",
		TranscodingURL:       "/Videos/item/master.m3u8",
	}
	got, method := selectPlaybackDelivery(source, false)
	if got != source.DirectStreamURL || method != "DirectStream" {
		t.Fatalf("selectPlaybackDelivery() = %q, %q", got, method)
	}
}

func TestSelectPlaybackDeliveryCanForceCompatibleTranscode(t *testing.T) {
	source := emby.MediaSourceInfo{
		SupportsDirectPlay: true,
		TranscodingURL:     "/Videos/item/master.m3u8",
	}
	got, method := selectPlaybackDelivery(source, true)
	if got != source.TranscodingURL || method != "Transcode" {
		t.Fatalf("selectPlaybackDelivery() = %q, %q", got, method)
	}
}

func TestSessionPlaybackCapabilitiesParseDecoderDetails(t *testing.T) {
	legacy := sessionPlaybackCapabilities(store.Session{})
	if legacy.HEVC {
		t.Fatal("legacy client must not implicitly claim HEVC")
	}
	got := sessionPlaybackCapabilities(store.Session{ClientCapabilities: []string{
		"video_h264_profile_high", "video_h264_level_52", "video_h264_max_3840x2160",
		"video_hevc_decode", "video_hevc_profile_main10", "video_hevc_main10_level_153",
		"video_hevc_max_3840x2160", "video_hevc_hdr10",
	}})
	if !got.HEVC || !got.HEVCMain10 || !got.HEVCHDR10 || got.HEVCMain10Level != 153 {
		t.Fatalf("HEVC capabilities = %+v", got)
	}
	if got.H264Level != 52 || got.H264MaxWidth != 3840 || got.H264MaxHeight != 2160 {
		t.Fatalf("H264 capabilities = %+v", got)
	}
}

func TestSubtitleMIMEFallsBackToDeliveryExtension(t *testing.T) {
	if got := subtitleMIME("", "https://emby.example/subtitles/4/stream.vtt?api_key=x"); got != "text/vtt" {
		t.Fatalf("subtitleMIME delivery fallback = %q", got)
	}
}
