package ch.threema.app.threemasafe

import ch.threema.app.managers.ServiceManager
import io.mockk.every
import io.mockk.mockkObject
import io.mockk.unmockkObject
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull

class ThreemaSafeServerInfoTest {

    @BeforeTest
    fun setUp() {
        // TODO(ANDR-4219): We have to mock ServiceManager, as it is sneakily referenced somewhere deep down the stack. This needs to be cleaned up.
        mockkObject(ServiceManager)
        every { ServiceManager.get() } returns null
    }

    @AfterTest
    fun tearDown() {
        unmockkObject(ServiceManager)
    }

    @Test
    fun `uses basic auth when username and password are available`() {
        val serverInfo = threemaSafeServerInfo(
            username = "username",
            password = "password",
        )
        assertEquals("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", serverInfo.authorization)
    }

    @Test
    fun `no authorization when username or password is empty`() {
        assertNull(threemaSafeServerInfo(username = "username", password = "").authorization)
        assertNull(threemaSafeServerInfo(username = "", password = "password").authorization)
        assertNull(threemaSafeServerInfo(username = "", password = "").authorization)
    }

    @Test
    fun `uses basic auth when username and password can be extracted from custom server name`() {
        val serverInfo = threemaSafeServerInfo(customServerName = "username:password@my-custom-server.threema.com")
        assertEquals("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", serverInfo.authorization)
    }

    @Test
    fun `empty username or password is ignored in custom server name`() {
        assertNull(threemaSafeServerInfo(customServerName = "username:@my-custom-server.threema.com").authorization)
        assertNull(threemaSafeServerInfo(customServerName = ":password@my-custom-server.threema.com").authorization)
        assertNull(threemaSafeServerInfo(customServerName = ":@my-custom-server.threema.com").authorization)
    }

    private fun threemaSafeServerInfo(customServerName: String? = null, username: String? = null, password: String? = null) =
        ThreemaSafeServerInfo(customServerName, username, password)
}
