package app.voltplan.cable.data

import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import app.voltplan.cable.analytics.Analytics
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.first

private val Context.dataStore by preferencesDataStore(name = "cable_settings")
private val UNIT_SYSTEM_KEY = stringPreferencesKey("unitSystem")
private val LAUNCHED_BEFORE_KEY = stringPreferencesKey("hasLaunchedBefore")

/**
 * App-wide unit preference, persisted via DataStore. Mirrors the iOS `UnitSystemSettings`
 * ObservableObject, including the "Unit System Changed" analytics event.
 */
class UnitSystemSettings(private val context: Context) {
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)

    private val _unitSystem = MutableStateFlow(
        runBlocking {
            val saved = context.dataStore.data.map { it[UNIT_SYSTEM_KEY] }.first()
            UnitSystem.fromRaw(saved) ?: UnitSystem.deviceDefault()
        },
    )
    val unitSystem: StateFlow<UnitSystem> = _unitSystem

    fun setUnitSystem(system: UnitSystem) {
        if (_unitSystem.value == system) return
        _unitSystem.value = system
        scope.launch {
            context.dataStore.edit { it[UNIT_SYSTEM_KEY] = system.rawValue }
        }
        Analytics.log("Unit System Changed", mapOf("system" to system.rawValue))
    }

    /** Returns true exactly once — on the first launch ever — mirroring the iOS UserDefaults flag. */
    suspend fun consumeFirstLaunch(): Boolean {
        val launched = context.dataStore.data.map { it[LAUNCHED_BEFORE_KEY] }.first()
        if (launched == null) {
            context.dataStore.edit { it[LAUNCHED_BEFORE_KEY] = "true" }
            return true
        }
        return false
    }
}
