/*
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package com.runicgateway.app.core.prefs

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
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.first
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton

private val Context.serverDataStore: DataStore<Preferences> by preferencesDataStore(name = "server")

/**
 * Persists the selected shard website base URL (PLAN.md §3). The base URL is
 * non-sensitive, so it lives in plain DataStore; tokens (M3) will use
 * EncryptedSharedPreferences instead, never this store.
 */
@Singleton
class ServerPreferences @Inject constructor(
    @param:dagger.hilt.android.qualifiers.ApplicationContext private val context: Context,
) {
    private val store = context.serverDataStore

    /** Emits the saved base URL, or null before first-run connect completes. */
    val baseUrl: Flow<String?> = store.data.map { it[KEY_BASE_URL] }

    suspend fun currentBaseUrl(): String? = baseUrl.first()

    suspend fun setBaseUrl(url: String) {
        store.edit { it[KEY_BASE_URL] = url }
    }

    /** Clears the base URL — used by a Settings → Server switch (hard reset, §3). */
    suspend fun clear() {
        store.edit { it.remove(KEY_BASE_URL) }
    }

    private companion object {
        val KEY_BASE_URL = stringPreferencesKey("base_url")
    }
}
