<?php
declare(strict_types=1);

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

final class WorkerHealthRecord
{
    public function __construct(
        private readonly string $workerId,
        private readonly WorkerHealthStatus $status,
        private readonly array $metrics = []
    ) {}

    public static function fromHeartbeat(WorkerHeartbeat $heartbeat, int $staleAfterSeconds = 60): self
    {
        $status = WorkerHealthStatus::fromHeartbeat($heartbeat, $staleAfterSeconds);
        $recorded = strtotime($heartbeat->recordedAt());

        return new self($heartbeat->workerId(), $status, [
            'handled' => $heartbeat->handled(),
            'failed' => $heartbeat->failed(),
            'lastEvent' => $heartbeat->lastEvent(),
            'lastHeartbeat' => $heartbeat->recordedAt(),
            'heartbeatAgeSeconds' => max(0, time() - $recorded),
        ]);
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['workerId'] ?? ''),
            new WorkerHealthStatus(
                (string) ($data['status']['state'] ?? WorkerHealthStatus::HEALTHY),
                (string) ($data['status']['reason'] ?? ''),
                (string) ($data['status']['checkedAt'] ?? '')
            ),
            (array) ($data['metrics'] ?? [])
        );
    }

    public function workerId(): string { return $this->workerId; }
    public function status(): WorkerHealthStatus { return $this->status; }
    public function metrics(): array { return $this->metrics; }

    public function toArray(): array
    {
        return [
            'workerId' => $this->workerId,
            'status' => $this->status->toArray(),
            'metrics' => $this->metrics,
        ];
    }
}
