package com.ponzischeme89.memby.data

import com.ponzischeme89.memby.data.model.MediaStream
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test

class SubtitleSupportTest {
    @Test
    fun `normalizes relative delivery urls and preserves selection metadata`() {
        val tracks = subtitleTracks(
            streams = listOf(
                MediaStream(
                    index = 3,
                    type = "Subtitle",
                    codec = "srt",
                    displayTitle = "English SDH",
                    language = "eng",
                    isDefault = true,
                    isForced = true,
                    isTextSubtitleStream = true,
                    deliveryUrl = "/Videos/a/Subtitles/3/Stream.srt?x=1",
                ),
            ),
            serverUrl = "https://emby.example",
            token = "a b",
            itemId = "item",
            mediaSourceId = "source",
        )

        assertEquals(1, tracks.size)
        assertEquals(
            "https://emby.example/Videos/a/Subtitles/3/Stream.srt?x=1&api_key=a+b",
            tracks.single().url,
        )
        assertEquals("application/x-subrip", tracks.single().mimeType)
        assertEquals("eng", tracks.single().language)
        assertTrue(tracks.single().isDefault)
        assertTrue(tracks.single().isForced)
        assertTrue(tracks.single().isHearingImpaired)
    }

    @Test
    fun `keeps supported text subtitles and rejects bitmap formats`() {
        assertEquals("text/vtt", subtitleMimeType("webvtt"))
        assertEquals("text/x-ssa", subtitleMimeType(null, "https://host/subtitle.ass?token=x"))
        assertEquals(null, subtitleMimeType("pgssub"))
        assertEquals(null, subtitleMimeType("dvdsub"))
    }

    @Test
    fun `does not duplicate authentication already present`() {
        assertEquals(
            "https://host/sub.srt?api_key=existing",
            authenticatedDeliveryUrl("https://other", "https://host/sub.srt?api_key=existing", "new"),
        )
    }

    @Test
    fun `image subtitles remain visible as encode choices without an overlay url`() {
        val track = subtitleTracks(
            streams = listOf(
                MediaStream(
                    index = 7,
                    type = "Subtitle",
                    codec = "pgssub",
                    language = "eng",
                    isForced = true,
                    deliveryMethod = "Encode",
                ),
            ),
            serverUrl = "https://emby.example",
            token = "token",
            itemId = "item",
            mediaSourceId = "source",
        ).single()

        assertEquals("Encode", track.deliveryMethod)
        assertEquals("", track.url)
        assertEquals("", track.mimeType)
        assertTrue(track.isForced)
    }
}
