/*
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package com.runicgateway.app.ui.admin

import com.runicgateway.app.R
import com.runicgateway.app.data.api.dto.SupportPageDto
import com.runicgateway.app.data.api.fake.FakeAdminApi
import com.runicgateway.app.data.repository.AdminRepository
import com.runicgateway.app.ui.UiState
import com.runicgateway.app.util.MainDispatcherRule
import com.runicgateway.app.util.errorUnit
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test

class AdminSupportViewModelTest {

    @get:Rule val mainDispatcher = MainDispatcherRule()

    private val api = FakeAdminApi()
    private fun viewModel() = AdminSupportViewModel(AdminRepository(api))

    @Test fun loadsOpenPagesOnInit() {
        api.supportPages = listOf(SupportPageDto(pageId = "0x1", message = "help"))
        val vm = viewModel()
        val pages = vm.state.value.pages
        assertTrue(pages is UiState.Success)
        assertEquals("0x1", (pages as UiState.Success).data.first().pageId)
    }

    @Test fun respondRejectsBlankMessage() {
        val vm = viewModel()
        vm.respond(id = "0x1", message = "   ", close = true)
        assertEquals(R.string.admin_support_message_required, vm.state.value.feedback!!.messageRes)
        assertEquals(null, api.lastRespond)
    }

    @Test fun respondTrimsMessageAndReloadsOnSuccess() {
        api.supportPages = listOf(SupportPageDto(pageId = "0x1"))
        val vm = viewModel()
        vm.respond(id = "0x1", message = "  on it ", close = false)
        assertEquals("on it", api.lastRespond!!.second.message)
        assertTrue(vm.state.value.feedback!!.ok)
    }

    @Test fun respondUnknownPageMapsTo404Copy() {
        api.unitResponse = errorUnit(404)
        val vm = viewModel()
        vm.respond(id = "0xZ", message = "hi", close = false)
        assertEquals(R.string.admin_support_unknown_page, vm.state.value.feedback!!.messageRes)
    }

    @Test fun closeShardOfflineMapsTo503Copy() {
        api.unitResponse = errorUnit(503)
        val vm = viewModel()
        vm.close("0x1")
        assertEquals(R.string.admin_mod_shard_offline, vm.state.value.feedback!!.messageRes)
    }
}
