<?php

declare(strict_types=1);

namespace App\Application\Admin\ValueObjects;

final readonly class BreadcrumbCollection
{
    /** @param array<Breadcrumb> $breadcrumbs */
    public function __construct(
        public array $breadcrumbs
    ) {
    }

    public static function fromArray(array $data): self
    {
        $breadcrumbs = [];
        foreach ($data as $breadcrumbData) {
            $breadcrumbs[] = Breadcrumb::fromArray($breadcrumbData);
        }

        return new self($breadcrumbs);
    }

    public function toArray(): array
    {
        return array_map(
            fn (Breadcrumb $breadcrumb) => $breadcrumb->toArray(),
            $this->breadcrumbs
        );
    }

    public function add(Breadcrumb $breadcrumb): self
    {
        return new self([...$this->breadcrumbs, $breadcrumb]);
    }

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

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

    public function getLast(): ?Breadcrumb
    {
        if (empty($this->breadcrumbs)) {
            return null;
        }

        return end($this->breadcrumbs);
    }
}
