package com.atridad.magiccounter.ui.settings

import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.serialization.Serializable

@Serializable
data class MatchRecord(
    val id: String,
    val name: String,
    val startedAtEpochMs: Long,
    val lastUpdatedEpochMs: Long,
    val ongoing: Boolean,
    val winnerPlayerId: Int? = null,
    val state: com.atridad.magiccounter.ui.state.GameState
)

enum class ThemeMode { System, Light, Dark }

private val Context.dataStore by preferencesDataStore(name = "app_settings")

object AppSettingsRepository {
    // Use a tolerant JSON instance to handle backward/forward compatible schema changes
    private val json = Json { ignoreUnknownKeys = true }
    private val THEME_MODE = intPreferencesKey("theme_mode")
    private val MATCH_HISTORY = stringPreferencesKey("match_history_json")

    fun themeMode(context: Context): Flow<ThemeMode> =
        context.dataStore.data.map { prefs ->
            when (prefs[THEME_MODE]) {
                1 -> ThemeMode.Light
                2 -> ThemeMode.Dark
                else -> ThemeMode.System
            }
        }

    suspend fun setThemeMode(context: Context, mode: ThemeMode) {
        context.dataStore.edit { prefs ->
            prefs[THEME_MODE] = when (mode) {
                ThemeMode.System -> 0
                ThemeMode.Light -> 1
                ThemeMode.Dark -> 2
            }
        }
    }

    // JSON blob to persist match history
    fun readMatchHistory(context: Context): Flow<List<MatchRecord>> =
        context.dataStore.data.map { prefs ->
            prefs[MATCH_HISTORY]?.let {
                runCatching { json.decodeFromString<List<MatchRecord>>(it) }.getOrDefault(emptyList())
            } ?: emptyList()
        }

    suspend fun writeMatchHistory(context: Context, history: List<MatchRecord>) {
        val jsonStr = json.encodeToString(history)
        context.dataStore.edit { prefs ->
            prefs[MATCH_HISTORY] = jsonStr
        }
    }
}


