<?php

declare(strict_types=1);

namespace PpPhp\Core\Discovery;

final class DiscoveryResult
{
    /** @var DiscoveryItem[] */
    private array $items = [];

    /** @var string[] */
    private array $errors = [];

    public function add(DiscoveryItem $item): void
    {
        $this->items[] = $item;
    }

    public function error(string $message): void
    {
        $this->errors[] = $message;
    }

    /** @return DiscoveryItem[] */
    public function items(): array
    {
        return $this->items;
    }

    /** @return string[] */
    public function errors(): array
    {
        return $this->errors;
    }

    public function merge(self $result): void
    {
        foreach ($result->items() as $item) {
            $this->add($item);
        }

        foreach ($result->errors() as $error) {
            $this->error($error);
        }
    }

    public function toArray(): array
    {
        return [
            'items' => array_map(
                static fn (DiscoveryItem $item): array => $item->toArray(),
                $this->items
            ),
            'errors' => $this->errors,
        ];
    }
}
