package com.ponzischeme89.memby.update

import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test

/**
 * The update source is chosen by URL shape, and a manifest's apkUrl may be relative.
 * Both are easy to get subtly wrong and would strand every TV on an old build.
 */
class UpdateSourceTest {

    @Test
    fun `a json url is a static manifest`() {
        assertTrue(isManifestUrl("https://nas.example.com/memby/latest.json"))
        assertTrue(isManifestUrl("https://nas.example.com/memby/latest.JSON"))
        assertTrue(isManifestUrl("https://nas.example.com/memby/latest.json?v=2"))
    }

    @Test
    fun `a bare host is treated as gitea`() {
        assertFalse(isManifestUrl("https://g.sublogue.com"))
        assertFalse(isManifestUrl("https://g.sublogue.com/"))
        // A folder that merely contains json elsewhere is not a manifest.
        assertFalse(isManifestUrl("https://nas.example.com/json"))
    }

    @Test
    fun `an absolute apk url is used as-is`() {
        val resolved = resolveApkUrl(
            "https://nas.example.com/memby/latest.json",
            "https://cdn.example.com/memby-0.1.54.apk",
        )
        assertEquals("https://cdn.example.com/memby-0.1.54.apk", resolved)
    }

    @Test
    fun `a relative apk url resolves next to the manifest`() {
        val resolved = resolveApkUrl(
            "https://nas.example.com/memby/latest.json",
            "memby-0.1.54.apk",
        )
        assertEquals("https://nas.example.com/memby/memby-0.1.54.apk", resolved)
    }

    @Test
    fun `a root-relative apk url keeps the host`() {
        val resolved = resolveApkUrl(
            "https://nas.example.com/memby/latest.json",
            "/downloads/memby-0.1.54.apk",
        )
        assertEquals("https://nas.example.com/downloads/memby-0.1.54.apk", resolved)
    }

    @Test
    fun `a query string on the manifest does not leak into the apk url`() {
        val resolved = resolveApkUrl(
            "https://nas.example.com/memby/latest.json?nocache=1",
            "memby-0.1.54.apk",
        )
        assertEquals("https://nas.example.com/memby/memby-0.1.54.apk", resolved)
    }

    @Test
    fun `manifest decodes with the field names the release script writes`() {
        val json = kotlinx.serialization.json.Json { ignoreUnknownKeys = true }
        val manifest = json.decodeFromString<UpdateManifest>(
            """{"version":"0.1.54","apkUrl":"memby-0.1.54.apk","notes":"Faster home screen"}""",
        )

        assertEquals("0.1.54", manifest.version)
        assertEquals("memby-0.1.54.apk", manifest.apkUrl)
        assertEquals("Faster home screen", manifest.notes)
    }
}
