<?php

namespace App\Modules\HR\Employees\Repositories;

use App\Modules\HR\Employees\Models\Employee;

class EmployeeHierarchyRepository
{
    public function hasActiveDirectReports(int $tenantId, int $managerEmployeeId): bool
    {
        return Employee::query()
            ->where('tenant_id', $tenantId)
            ->where('manager_employee_id', $managerEmployeeId)
            ->where('is_active', true)
            ->exists();
    }

    /**
     * Active employees in the reporting tree under a manager (all levels).
     *
     * @return list<int>
     */
    public function activeDescendantIds(int $tenantId, int $managerEmployeeId, int $maxDepth = 20): array
    {
        $frontier = [$managerEmployeeId];
        $descendants = [];
        $depth = 0;

        while ($frontier !== [] && $depth < $maxDepth) {
            $children = Employee::query()
                ->where('tenant_id', $tenantId)
                ->where('is_active', true)
                ->whereIn('manager_employee_id', $frontier)
                ->pluck('id')
                ->all();

            if ($children === []) {
                break;
            }

            $descendants = array_merge($descendants, $children);
            $frontier = $children;
            $depth++;
        }

        return array_values(array_unique(array_map('intval', $descendants)));
    }

    /**
     * @param  list<int>  $employeeIds
     * @return array<int, string>
     */
    public function namesById(int $tenantId, array $employeeIds): array
    {
        if ($employeeIds === []) {
            return [];
        }

        return Employee::query()
            ->where('tenant_id', $tenantId)
            ->whereIn('id', $employeeIds)
            ->orderBy('full_name')
            ->pluck('full_name', 'id')
            ->all();
    }
}
