<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Rules\Repository;

final class RuleRegistry
{
    /** @param RuleRepositoryEntry[] $entries */
    public function __construct(private readonly array $entries = []) {}

    public function active(): array
    {
        return array_values(array_filter($this->entries, static fn (RuleRepositoryEntry $entry): bool => $entry->active()));
    }

    public function forRuleSet(string $ruleSetId): array
    {
        return array_values(array_filter($this->entries, static fn (RuleRepositoryEntry $entry): bool => $entry->ruleSetId() === $ruleSetId));
    }

    public function find(string $ruleId): ?RuleRepositoryEntry
    {
        foreach ($this->entries as $entry) {
            if ($entry->ruleId() === $ruleId) {
                return $entry;
            }
        }

        return null;
    }

    public function latest(string $ruleId): ?RuleRepositoryEntry
    {
        $matches = array_values(array_filter($this->entries, static fn (RuleRepositoryEntry $entry): bool => $entry->ruleId() === $ruleId));
        usort($matches, static fn (RuleRepositoryEntry $a, RuleRepositoryEntry $b): int => version_compare($b->version(), $a->version()));
        return $matches[0] ?? null;
    }
}
