package com.bytelyst.platform

import kotlinx.coroutines.test.runTest
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test

class BLKillSwitchClientTest {

    private lateinit var server: MockWebServer
    private lateinit var config: BLPlatformConfig

    @BeforeEach
    fun setup() {
        server = MockWebServer()
        server.start()
        config = BLPlatformConfig(
            productId = "testapp",
            baseUrl = server.url("/api").toString().trimEnd('/'),
            applicationId = "com.test.app",
        )
    }

    @AfterEach
    fun teardown() {
        server.shutdown()
    }

    @Test
    fun `returns ok when not disabled`() = runTest {
        server.enqueue(
            MockResponse()
                .setBody("""{"disabled":false}""")
                .setResponseCode(200)
        )

        val client = BLKillSwitchClient(config)
        val result = client.check()

        assertFalse(result.disabled)
        assertNull(result.message)
    }

    @Test
    fun `returns disabled with message`() = runTest {
        server.enqueue(
            MockResponse()
                .setBody("""{"disabled":true,"message":"Maintenance in progress"}""")
                .setResponseCode(200)
        )

        val client = BLKillSwitchClient(config)
        val result = client.check()

        assertTrue(result.disabled)
        assertEquals("Maintenance in progress", result.message)
    }

    @Test
    fun `fail-open on server error`() = runTest {
        server.enqueue(MockResponse().setResponseCode(500))

        val client = BLKillSwitchClient(config)
        val result = client.check()

        assertFalse(result.disabled)
        assertNull(result.message)
    }

    @Test
    fun `fail-open on network error`() = runTest {
        server.shutdown() // Force connection failure

        val client = BLKillSwitchClient(config)
        val result = client.check()

        assertFalse(result.disabled)
    }

    @Test
    fun `sends correct query parameters`() = runTest {
        server.enqueue(
            MockResponse()
                .setBody("""{"disabled":false}""")
                .setResponseCode(200)
        )

        val client = BLKillSwitchClient(config)
        client.check()

        val recorded = server.takeRequest()
        assertTrue(recorded.path!!.contains("platform=android"))
        assertEquals("GET", recorded.method)
    }

    @Test
    fun `sends X-Product-Id header`() = runTest {
        server.enqueue(
            MockResponse()
                .setBody("""{"disabled":false}""")
                .setResponseCode(200)
        )

        val client = BLKillSwitchClient(config)
        client.check()

        val recorded = server.takeRequest()
        assertEquals("testapp", recorded.getHeader("X-Product-Id"))
    }
}
