<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Worker;

final class WorkerStatistics
{
    public function __construct(
        private readonly int $workers = 0,
        private readonly int $running = 0,
        private readonly int $idle = 0,
        private readonly int $stopped = 0,
        private readonly int $handled = 0,
        private readonly int $failed = 0
    ) {}

    public function recordWorker(string $state): self
    {
        return new self(
            $this->workers + 1,
            $this->running + ($state === WorkerStatus::RUNNING ? 1 : 0),
            $this->idle + ($state === WorkerStatus::IDLE ? 1 : 0),
            $this->stopped + ($state === WorkerStatus::STOPPED ? 1 : 0),
            $this->handled,
            $this->failed
        );
    }

    public function recordResult(WorkerResult $result): self
    {
        return new self(
            $this->workers,
            $this->running,
            $this->idle,
            $this->stopped,
            $this->handled + 1,
            $this->failed + ($result->ok() ? 0 : 1)
        );
    }

    public function toArray(): array
    {
        return [
            'workers' => $this->workers,
            'running' => $this->running,
            'idle' => $this->idle,
            'stopped' => $this->stopped,
            'handled' => $this->handled,
            'failed' => $this->failed,
        ];
    }
}
