<?php

declare(strict_types=1);

namespace App\Application\Admin\ValueObjects;

final readonly class RouteCollection implements \IteratorAggregate, \Countable
{
    /**
     * @param list<array<string, mixed>> $routes
     */
    public function __construct(
        private array $routes = []
    ) {
    }

    /**
     * @param list<array<string, mixed>> $routes
     */
    public static function fromArray(array $routes): self
    {
        return new self($routes);
    }

    public function count(): int
    {
        return count($this->routes);
    }

    public function isEmpty(): bool
    {
        return empty($this->routes);
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function toArray(): array
    {
        return $this->routes;
    }

    public function filterByMethod(string $method): self
    {
        $filtered = array_filter($this->routes, function (array $route) use ($method) {
            return ($route['method'] ?? 'GET') === $method;
        });

        return new self(array_values($filtered));
    }

    public function filterByPattern(string $pattern): self
    {
        $filtered = array_filter($this->routes, function (array $route) use ($pattern) {
            return isset($route['path']) && str_contains($route['path'], $pattern);
        });

        return new self(array_values($filtered));
    }

    /**
     * @return \ArrayIterator<int, array<string, mixed>>
     */
    public function getIterator(): \ArrayIterator
    {
        return new \ArrayIterator($this->routes);
    }
}
