/*
 * 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.AdminCountsDto
import com.runicgateway.app.data.api.dto.AdminDashboardDto
import com.runicgateway.app.data.api.dto.SiteModeStateDto
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.httpError
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test

class AdminDashboardViewModelTest {

    @get:Rule val mainDispatcher = MainDispatcherRule()

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

    @Test fun loadsDashboardOnInit() {
        api.dashboard = AdminDashboardDto(siteMode = "live", counts = AdminCountsDto(users = 12))
        val vm = viewModel()
        val state = vm.state.value.dashboard
        assertTrue(state is UiState.Success)
        assertEquals(12, (state as UiState.Success).data.counts.users)
    }

    @Test fun loadSurfacesServerErrorAsUiError() {
        api.error = httpError(500)
        val vm = viewModel()
        assertTrue(vm.state.value.dashboard is UiState.Error)
    }

    @Test fun setSiteModeSuccessUpdatesModeAndClearsSwitching() {
        api.dashboard = AdminDashboardDto(siteMode = "live")
        api.siteMode = SiteModeStateDto(siteMode = "maintenance")
        val vm = viewModel()
        vm.setSiteMode("maintenance")
        val s = vm.state.value
        assertFalse(s.switching)
        assertTrue(s.feedback!!.ok)
        assertEquals(R.string.admin_site_mode_updated, s.feedback!!.messageRes)
    }

    @Test fun setSiteModeForbiddenShowsForbiddenCopy() {
        api.dashboard = AdminDashboardDto()
        api.error = httpError(403)
        val vm = viewModel()
        vm.setSiteMode("maintenance")
        val fb = vm.state.value.feedback!!
        assertFalse(fb.ok)
        assertEquals(R.string.admin_forbidden, fb.messageRes)
    }

    @Test fun clearFeedbackResetsBanner() {
        api.error = httpError(500)
        val vm = viewModel()
        vm.setSiteMode("live")
        vm.clearFeedback()
        assertEquals(null, vm.state.value.feedback)
    }
}
