package com.tomhempel.rbarometer.network

import android.content.Context
import com.tomhempel.rbarometer.security.SensitiveDataCrypto

/** Persists per-client answer sync timestamps (survives process restarts). */
internal object ClientAnswerSyncStore {
    private const val PREFS = "client_answer_sync_v1"

    fun lastPullMs(context: Context, clientCode: String): Long {
        val key = normalize(clientCode) ?: return 0L
        return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getLong(key, 0L)
    }

    fun markPulled(context: Context, clientCode: String, atMs: Long = System.currentTimeMillis()) {
        val key = normalize(clientCode) ?: return
        context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
            .edit()
            .putLong(key, atMs)
            .apply()
    }

    fun markPulledBatch(context: Context, clientCodes: List<String>, atMs: Long = System.currentTimeMillis()) {
        if (clientCodes.isEmpty()) return
        val edit = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
        for (code in clientCodes) {
            val key = normalize(code) ?: continue
            edit.putLong(key, atMs)
        }
        edit.apply()
    }

    fun clear(context: Context, clientCode: String? = null) {
        val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
        if (clientCode.isNullOrBlank()) {
            prefs.edit().clear().apply()
        } else {
            normalize(clientCode)?.let { prefs.edit().remove(it).apply() }
            prefs.edit().remove(clientCode.trim().uppercase()).apply()
        }
    }

    private fun normalize(clientCode: String): String? =
        clientCode.trim()
            .takeIf { it.isNotBlank() }
            ?.uppercase()
            ?.let { SensitiveDataCrypto.clientCodeKey(it) }
}
