package com.ponzischeme89.memby.data

import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test

/**
 * The gateway's 503 body is the only thing allowed to put words on the maintenance
 * screen, so what gets trusted out of it matters.
 */
class MaintenanceMessageTest {

    @Test
    fun `reads the operator's message`() {
        val body = """{"error":"Back at 9pm","maintenance":true,"message":"Back at 9pm"}"""

        assertEquals("Back at 9pm", parseMaintenanceMessage(body))
    }

    @Test
    fun `ignores a 503 that is not a maintenance response`() {
        // Some proxy or upstream returning its own 503 must not get to write on screen.
        assertNull(parseMaintenanceMessage("""{"message":"upstream connect error"}"""))
        assertNull(parseMaintenanceMessage("""{"maintenance":false,"message":"nope"}"""))
    }

    @Test
    fun `survives a body that is not the shape we expect`() {
        assertNull(parseMaintenanceMessage(""))
        assertNull(parseMaintenanceMessage("   "))
        assertNull(parseMaintenanceMessage("<html>502 Bad Gateway</html>"))
        assertNull(parseMaintenanceMessage("""{"maintenance":true"""))
    }

    @Test
    fun `blank and whitespace-only messages are rejected`() {
        assertNull(parseMaintenanceMessage("""{"maintenance":true,"message":"   "}"""))
        assertNull(parseMaintenanceMessage("""{"maintenance":true}"""))
    }

    @Test
    fun `an over-long message is truncated to something that fits a screen`() {
        val long = "x".repeat(400)
        val parsed = parseMaintenanceMessage("""{"maintenance":true,"message":"$long"}""")

        assertEquals(160, parsed?.length)
    }

    @Test
    fun `unknown fields from a newer gateway are ignored`() {
        val body = """{"maintenance":true,"message":"Upgrading","until":"2026-07-27T22:00:00Z"}"""

        assertEquals("Upgrading", parseMaintenanceMessage(body))
    }
}
