package com.tomhempel.rbarometer.ui

import android.content.Context
import com.tomhempel.rbarometer.LanguageManager
import com.tomhempel.rbarometer.data.UnuploadedWorkRepository
import com.tomhempel.rbarometer.network.ClientAnswerSyncStore
import com.tomhempel.rbarometer.network.NetworkUtils
import com.tomhempel.rbarometer.network.QuestionnaireCache
import com.tomhempel.rbarometer.network.TokenStore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * User-initiated logout: requires online + no unuploaded local work, then wipes all local data.
 */
object SessionLogout {

    sealed class BlockReason {
        data object Offline : BlockReason()
        data class UnuploadedWork(val summary: UnuploadedWorkRepository.Summary) : BlockReason()
    }

    suspend fun evaluate(context: Context): BlockReason? {
        if (!NetworkUtils.isOnline(context)) return BlockReason.Offline
        val summary = UnuploadedWorkRepository.summarize()
        if (summary.hasBlockingWork) return BlockReason.UnuploadedWork(summary)
        return null
    }

    suspend fun wipeAllLocalData(context: Context) {
        withContext(Dispatchers.IO) {
            QuestionnaireCache.wipeEntireLocalStore(context)
            ClientAnswerSyncStore.clear(context)
            ClientRecentStore.clear(context)
            TokenStore.clear(context)
        }
    }

    fun formatPendingDetails(languageId: String, summary: UnuploadedWorkRepository.Summary): String {
        val parts = mutableListOf<String>()
        if (summary.pendingQuestionnaires > 0) {
            parts += format(languageId, "logout_pending_detail_questionnaires", summary.pendingQuestionnaires)
        }
        if (summary.pendingScoringReviews > 0) {
            parts += format(languageId, "logout_pending_detail_scoring", summary.pendingScoringReviews)
        }
        if (summary.inProgressQuestionnaires > 0) {
            parts += format(languageId, "logout_pending_detail_in_progress", summary.inProgressQuestionnaires)
        }
        return parts.joinToString("\n")
    }

    fun message(languageId: String, key: String, fallback: String): String {
        val raw = runCatching { LanguageManager.getText(languageId, key) }.getOrDefault(fallback)
        val cleaned = raw.trim().removePrefix("[").removeSuffix("]")
        return if (cleaned.equals(key, ignoreCase = true) || cleaned.isBlank()) fallback else cleaned
    }

    private fun format(languageId: String, key: String, count: Int): String {
        val template = message(languageId, key, key)
        return template.replace("{count}", count.toString())
    }
}
