package com.tomhempel.rbarometer.ui

import android.content.Context
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey

/** Persists the last few client codes chosen by the coach for quick re-selection. */
object ClientRecentStore {
    private const val PREFS = "client_recent"
    private const val LEGACY_PREFS = "client_recent"
    private const val KEY_CODES = "codes"
    private const val MAX = 5
    private const val SEP = "\u0001"

    fun record(context: Context, clientCode: String) {
        val code = clientCode.trim()
        if (code.isBlank()) return
        val prefs = prefs(context)
        val updated = listOf(code) + loadList(prefs).filter { !it.equals(code, ignoreCase = true) }
        prefs.edit().putString(KEY_CODES, updated.take(MAX).joinToString(SEP)).apply()
        clearLegacy(context)
    }

    fun getRecent(context: Context): List<String> =
        loadList(prefs(context)).ifEmpty {
            val legacy = loadList(context.getSharedPreferences(LEGACY_PREFS, Context.MODE_PRIVATE))
            if (legacy.isNotEmpty()) {
                prefs(context).edit().putString(KEY_CODES, legacy.take(MAX).joinToString(SEP)).apply()
                clearLegacy(context)
            }
            legacy
        }

    fun clear(context: Context) {
        prefs(context).edit().clear().apply()
        clearLegacy(context)
    }

    private fun prefs(context: Context) = EncryptedSharedPreferences.create(
        context,
        "${PREFS}_secure",
        MasterKey.Builder(context)
            .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
            .build(),
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
    )

    private fun loadList(prefs: android.content.SharedPreferences): List<String> {
        val raw = prefs.getString(KEY_CODES, null) ?: return emptyList()
        return raw.split(SEP).map { it.trim() }.filter { it.isNotBlank() }
    }

    private fun clearLegacy(context: Context) {
        context.getSharedPreferences(LEGACY_PREFS, Context.MODE_PRIVATE).edit().clear().apply()
    }
}
