package dev.inmo.postssystem.features.roles.common.keyvalue

import dev.inmo.postssystem.features.roles.common.*
import dev.inmo.micro_utils.repos.*
import kotlinx.serialization.KSerializer
import kotlinx.serialization.StringFormat

open class WriteKeyValueRolesStorage<T : Role>(
    private val keyValuesRepo: WriteKeyValuesRepo<String, String>,
    private val serializer: KSerializer<T>,
    private val format: StringFormat = ReadKeyValueRolesStorage.defaultJson
) : WriteRolesStorage<T> {
    override suspend fun include(subject: RoleSubject, role: T): Boolean {
        return runCatching {
            keyValuesRepo.add(
                format.encodeToString(RoleSubject.serializer(), subject),
                format.encodeToString(serializer, role)
            )
            true
        }.getOrElse { false }
    }

    override suspend fun exclude(subject: RoleSubject, role: T): Boolean {
        return runCatching {
            keyValuesRepo.remove(
                format.encodeToString(RoleSubject.serializer(), subject),
                format.encodeToString(serializer, role)
            )
            true
        }.getOrElse { false }
    }
}
