package com.betriebsratkanzlei.legalconsenthub.user

import com.betriebsratkanzlei.legalconsenthub_api.model.UserRole
import org.springframework.stereotype.Component

@Component
object UserRoleConverter {

    fun getRolesForOrganization(organizationRoles: Set<UserOrganizationRole>, organizationId: String): List<UserRole> {
        return organizationRoles
            .filter { it.organizationId == organizationId }
            .mapNotNull { orgRole ->
                try {
                    UserRole.valueOf(orgRole.role)
                } catch (e: IllegalArgumentException) {
                    null
                }
            }
    }

    fun setRolesForOrganization(organizationRoles: MutableSet<UserOrganizationRole>, organizationId: String, roles: List<UserRole>) {
        organizationRoles.removeIf { it.organizationId == organizationId }
        roles.forEach { role ->
            organizationRoles.add(UserOrganizationRole(organizationId, role.name))
        }
    }

    fun convertToMap(organizationRoles: Set<UserOrganizationRole>): Map<String, List<UserRole>> {
        return organizationRoles
            .groupBy { it.organizationId }
            .mapValues { (_, roles) ->
                roles.mapNotNull { orgRole ->
                    try {
                        UserRole.valueOf(orgRole.role)
                    } catch (e: IllegalArgumentException) {
                        null
                    }
                }
            }
            .filterValues { it.isNotEmpty() }
    }
}
