package com.anypreta.bountyboard.data

import android.content.Context
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

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

/** Persists the configurable base URL and the selected theme. */
class SettingsStore(private val context: Context) {

    private val keyBaseUrl = stringPreferencesKey("base_url")
    private val keyTheme = stringPreferencesKey("theme")
    private val keyPush = booleanPreferencesKey("push_enabled")

    val baseUrl: Flow<String> = context.dataStore.data.map { it[keyBaseUrl] ?: DEFAULT_BASE_URL }
    val theme: Flow<String> = context.dataStore.data.map { it[keyTheme] ?: "light" }
    val pushEnabled: Flow<Boolean> = context.dataStore.data.map { it[keyPush] ?: true }

    suspend fun setBaseUrl(url: String) {
        context.dataStore.edit { it[keyBaseUrl] = url }
    }

    suspend fun setTheme(theme: String) {
        context.dataStore.edit { it[keyTheme] = theme }
    }

    suspend fun setPushEnabled(enabled: Boolean) {
        context.dataStore.edit { it[keyPush] = enabled }
    }

    companion object {
        const val DEFAULT_BASE_URL = "https://bountyboard.anypreta.com/"
    }
}
