TeamScope.kt

// EV Supervision Lite — built by Kevin Vavelin, Codetics
// https://codetics.fr
// Copyright (c) 2026 Kevin Vavelin, Codetics
// SPDX-License-Identifier: LicenseRef-Codetics-Attribution-1.0

package fr.codetics.ev_server.services.fleet

import fr.codetics.ev_server.core.AppPrincipal
import fr.codetics.ev_server.models.entities.UserEntity
import fr.codetics.ev_server.models.people.UserRole
import fr.codetics.ev_server.persistence.Queries
import fr.codetics.ev_server.persistence.eq
import fr.codetics.ev_server.persistence.list
import java.util.UUID
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service

/**
 * Who a B2B account may follow. Administrators, operators and viewers see the whole workspace.
 * A MANAGER sees themself and every employee who reports to them, directly or through other managers.
 */
@Service
class TeamScope(private val queries: Queries) {
    fun employees(tenant: UUID): List<UserEntity> =
        queries.list<UserEntity>(listOf(eq("tenantId", tenant), eq("deletedAt", null)), Sort.by("displayName", "email"))

    /** The user ids [user] may see, or null for the whole workspace. */
    fun members(user: AppPrincipal, everyone: List<UserEntity> = employees(user.tenantId)): Set<UUID>? {
        if (user.role != UserRole.MANAGER) return null
        val reports = everyone.groupBy { it.managerId }
        val seen = linkedSetOf(user.id)
        val queue = ArrayDeque(listOf(user.id))
        while (queue.isNotEmpty()) {
            reports[queue.removeFirst()].orEmpty().forEach { employee ->
                if (seen.add(employee.id)) queue.addLast(employee.id)
            }
        }
        return seen
    }

    fun covers(user: AppPrincipal, target: UUID?): Boolean {
        val members = members(user) ?: return true
        return target != null && target in members
    }
}