package com.anypreta.bountyboard.data.push

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 com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.flow.first

private val Context.pushDataStore by preferencesDataStore(name = "bb_push_state")

/**
 * Remembers what we've already raised a system notification for, so background
 * polls only notify on genuinely new alerts/messages (and never spam the entire
 * backlog on the first run after install/login).
 */
class PushStateStore(private val context: Context) {

    private val gson = Gson()
    private val keySeeded = booleanPreferencesKey("seeded")
    private val keyLastNotif = stringPreferencesKey("last_notif_id")
    private val keyConvSeen = stringPreferencesKey("conv_seen") // JSON map id -> lastMessageAt

    suspend fun seeded(): Boolean = context.pushDataStore.data.first()[keySeeded] ?: false

    suspend fun lastNotificationId(): String? = context.pushDataStore.data.first()[keyLastNotif]

    suspend fun convSeen(): Map<String, String> {
        val raw = context.pushDataStore.data.first()[keyConvSeen] ?: return emptyMap()
        return try {
            gson.fromJson(raw, object : TypeToken<Map<String, String>>() {}.type) ?: emptyMap()
        } catch (_: Exception) {
            emptyMap()
        }
    }

    suspend fun update(seeded: Boolean, lastNotificationId: String?, convSeen: Map<String, String>) {
        context.pushDataStore.edit {
            it[keySeeded] = seeded
            if (lastNotificationId != null) it[keyLastNotif] = lastNotificationId
            it[keyConvSeen] = gson.toJson(convSeen)
        }
    }

    suspend fun clear() {
        context.pushDataStore.edit { it.clear() }
    }
}
