<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Worker\Pool;

use PpPhp\Core\Platform\Event\Worker\Contracts\WorkerInterface;

final class WorkerPoolRegistry
{
    private array $records = [];

    public function register(WorkerInterface $worker, int $capacity = 1, array $metadata = []): void
    {
        $record = WorkerPoolRecord::fromWorker($worker, $capacity, $metadata);
        $this->records[$record->id()] = $record;
    }

    public function addRecord(WorkerPoolRecord $record): void
    {
        $this->records[$record->id()] = $record;
    }

    public function remove(string $id): bool
    {
        if (!isset($this->records[$id])) {
            return false;
        }
        unset($this->records[$id]);
        return true;
    }

    public function get(string $id): ?WorkerPoolRecord
    {
        return $this->records[$id] ?? null;
    }

    public function replace(WorkerPoolRecord $record): void
    {
        $this->records[$record->id()] = $record;
    }

    public function all(): array
    {
        return array_values($this->records);
    }

    public function available(): array
    {
        return array_values(array_filter($this->records, static fn (WorkerPoolRecord $record): bool => $record->available()));
    }

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

    public function toArray(): array
    {
        return array_map(static fn (WorkerPoolRecord $record): array => $record->toArray(), $this->all());
    }
}
