package com.tomhempel.rbarometer.data

import com.tomhempel.rbarometer.MyApp
import com.tomhempel.rbarometer.security.SensitiveDataCrypto

object ClientRepository {

    private val dao get() = MyApp.database.clientDao()

    suspend fun ensureClient(clientCode: String) {
        val key = SensitiveDataCrypto.clientCodeKey(clientCode)
        if (dao.getByKey(key) != null) return
        dao.insertClient(
            Client(
                clientCodeKey = key,
                clientCodeEnc = SensitiveDataCrypto.encrypt(clientCode.trim()),
            ),
        )
    }

    suspend fun exists(clientCode: String): Boolean =
        dao.getByKey(SensitiveDataCrypto.clientCodeKey(clientCode)) != null

    suspend fun getAllClientCodes(): List<String> =
        dao.getAll().map { SensitiveDataCrypto.decrypt(it.clientCodeEnc) }

    suspend fun deleteAllClients() {
        dao.deleteAllClients()
    }

    suspend fun deleteClientsNotIn(clientCodes: List<String>) {
        val keys = clientCodes.map { SensitiveDataCrypto.clientCodeKey(it) }.distinct()
        if (keys.isEmpty()) {
            dao.deleteAllClients()
        } else {
            dao.deleteClientsNotIn(keys)
        }
    }

    suspend fun replaceClients(clientCodes: List<String>) {
        val codes = clientCodes.distinct()
        deleteClientsNotIn(codes)
        codes.forEach { ensureClient(it) }
    }
}
