<?php

declare(strict_types=1);

namespace App\Shared\Domain\Module;

use InvalidArgumentException;

final class ModuleRegistry
{
    /**
     * @param list<class-string> $moduleClasses
     *
     * @return list<string>
     */
    public static function ids(array $moduleClasses): array
    {
        $ids = [];
        foreach ($moduleClasses as $moduleClass) {
            if (!is_a($moduleClass, ModuleInterface::class, true)) {
                continue;
            }
            $id = $moduleClass::id();
            if (in_array($id, $ids, true)) {
                throw new InvalidArgumentException(sprintf('Module ID "%s" déclaré plusieurs fois dans la configuration des modules.', $id));
            }
            $ids[] = $id;
        }

        return $ids;
    }

    /**
     * @param list<class-string> $moduleClasses
     *
     * @return list<array{code: string, label: string, module: string}>
     */
    public static function permissions(array $moduleClasses): array
    {
        $out = [];
        foreach ($moduleClasses as $moduleClass) {
            if (!is_a($moduleClass, ModuleInterface::class, true)) {
                continue;
            }
            $moduleId = $moduleClass::id();
            foreach ($moduleClass::permissions() as $perm) {
                $code = $perm['code'];
                if (!str_starts_with($code, $moduleId.'.')) {
                    throw new InvalidArgumentException(sprintf('Permission "%s" du module "%s" doit être préfixée par "%s.".', $code, $moduleId, $moduleId));
                }
                $out[] = ['code' => $code, 'label' => $perm['label'], 'module' => $moduleId];
            }
        }

        return $out;
    }
}
