package dev.inmo.postssystem.features.roles.server

import dev.inmo.postssystem.features.roles.common.*

class RolesAggregator(
    private val otherStorages: List<RolesStorageHolder<*>>
) : RolesStorage<Role> {
    private val otherStoragesByClass = otherStorages.associateBy { it.kclass }

    override suspend fun getSubjects(role: Role): List<RoleSubject> {
        return otherStoragesByClass[role::class] ?.getUsers(role) ?: emptyList()
    }

    override suspend fun getRoles(subject: RoleSubject): List<Role> = otherStorages.flatMap { it.getRoles(subject) }

    override suspend fun contains(subject: RoleSubject, role: Role): Boolean {
        return otherStoragesByClass[role::class] ?.contains(subject, role) ?: false
    }

    override suspend fun containsAny(subject: RoleSubject, roles: List<Role>): Boolean {
        return roles.any {
            contains(subject, it)
        }
    }

    override suspend fun include(
        subject: RoleSubject,
        role: Role
    ): Boolean = otherStoragesByClass[role::class] ?.include(subject, role) ?: false

    override suspend fun exclude(
        subject: RoleSubject,
        role: Role
    ): Boolean {
        return otherStoragesByClass[role::class] ?.exclude(subject, role) ?: false
    }
}
