package com.ponzischeme89.memby.data

import com.ponzischeme89.memby.data.model.GatewayUpdate
import kotlinx.serialization.json.Json
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test

/**
 * The update verdict decides whether a viewer can use the app at all, so the client's
 * reading of it needs pinning down — including the cases that must NOT block anyone.
 */
class GatewayUpdateTest {

    private val json = Json { ignoreUnknownKeys = true; coerceInputValues = true }

    @Test
    fun `a mandatory verdict is actionable and blocking`() {
        val update = json.decodeFromString<GatewayUpdate>(
            """{"status":"mandatory","version":"0.1.54","notes":"Security fix","downloadUrl":"https://nas/memby.apk"}""",
        )

        assertTrue(update.isMandatory)
        assertFalse(update.isOptional)
        assertTrue(update.isActionable)
        assertEquals("0.1.54", update.version)
    }

    @Test
    fun `an optional verdict is dismissable`() {
        val update = json.decodeFromString<GatewayUpdate>(
            """{"status":"optional","version":"0.1.54","downloadUrl":"https://nas/memby.apk","sha256":"abc","sizeBytes":123}""",
        )

        assertTrue(update.isOptional)
        assertFalse(update.isMandatory)
        assertTrue(update.isActionable)
        assertEquals("abc", update.sha256)
        assertEquals(123L, update.sizeBytes)
    }

    @Test
    fun `status none is never shown`() {
        val update = json.decodeFromString<GatewayUpdate>("""{"status":"none"}""")

        assertFalse(update.isActionable)
    }

    @Test
    fun `a verdict with no download url is not actionable`() {
        // Nothing to act on: showing an unblockable prompt with no working button would
        // strand the viewer completely.
        val update = json.decodeFromString<GatewayUpdate>(
            """{"status":"mandatory","version":"0.1.54","downloadUrl":""}""",
        )

        assertTrue(update.isMandatory)
        assertFalse(update.isActionable)
    }

    @Test
    fun `an empty response decodes to nothing to do`() {
        val update = json.decodeFromString<GatewayUpdate>("{}")

        assertEquals(GatewayUpdate.STATUS_NONE, update.status)
        assertFalse(update.isActionable)
    }

    @Test
    fun `an unrecognised status from a newer gateway is treated as nothing`() {
        val update = json.decodeFromString<GatewayUpdate>(
            """{"status":"nag","version":"0.1.54","downloadUrl":"https://nas/memby.apk"}""",
        )

        assertFalse(update.isMandatory)
        assertFalse(update.isOptional)
    }
}
