<?php
declare(strict_types=1);

namespace App\Foundation;

use InvalidArgumentException;

final class MetadataRegistry
{
    /** @var array<string,array<string,mixed>> */
    private array $entities = [];

    /** @param array<string,mixed> $definition */
    public function registerEntity(string $code, array $definition): void
    {
        if (!preg_match('/^[a-z][a-z0-9_.-]*$/', $code)) {
            throw new InvalidArgumentException('Code de métadonnée invalide : ' . $code);
        }

        $this->entities[$code] = array_merge([
            'code' => $code,
            'label' => $code,
            'fields' => [],
            'searchable' => false,
            'audited' => true,
        ], $definition);
    }

    /** @return array<string,mixed>|null */
    public function entity(string $code): ?array
    {
        return $this->entities[$code] ?? null;
    }

    /** @return array<string,array<string,mixed>> */
    public function all(): array
    {
        ksort($this->entities);
        return $this->entities;
    }
}
