<?php

declare(strict_types=1);

namespace App\Application\LiveComponents\Dashboard;

use App\Application\LiveComponents\LiveComponentState;

/**
 * Type-safe state for WorkerHealthComponent
 *
 * Provides real-time worker health monitoring.
 * Tracks active workers, job counts, and heartbeat status.
 */
final readonly class WorkerHealthState implements LiveComponentState
{
    public function __construct(
        public int $activeWorkers = 0,
        public int $totalWorkers = 0,
        public int $jobsInProgress = 0,
        public array $workerDetails = [], // ['worker_id' => ['jobs' => int, 'last_heartbeat' => string, 'healthy' => bool]]
        public string $lastUpdated = ''
    ) {}

    /**
     * Create from array data (from client or storage)
     */
    public static function fromArray(array $data): self
    {
        return new self(
            activeWorkers: (int) ($data['activeWorkers'] ?? $data['active_workers'] ?? 0),
            totalWorkers: (int) ($data['totalWorkers'] ?? $data['total_workers'] ?? 0),
            jobsInProgress: (int) ($data['jobsInProgress'] ?? $data['jobs_in_progress'] ?? 0),
            workerDetails: (array) ($data['workerDetails'] ?? $data['worker_details'] ?? []),
            lastUpdated: (string) ($data['lastUpdated'] ?? $data['last_updated'] ?? '')
        );
    }

    /**
     * Create empty state with defaults
     */
    public static function empty(): self
    {
        return new self();
    }

    /**
     * Update with fresh worker health data
     */
    public function withWorkerHealth(
        int $activeWorkers,
        int $totalWorkers,
        int $jobsInProgress,
        array $workerDetails
    ): self {
        return new self(
            activeWorkers: $activeWorkers,
            totalWorkers: $totalWorkers,
            jobsInProgress: $jobsInProgress,
            workerDetails: $workerDetails,
            lastUpdated: date('H:i:s')
        );
    }

    /**
     * Update timestamp
     */
    public function withLastUpdated(string $timestamp): self
    {
        return new self(
            activeWorkers: $this->activeWorkers,
            totalWorkers: $this->totalWorkers,
            jobsInProgress: $this->jobsInProgress,
            workerDetails: $this->workerDetails,
            lastUpdated: $timestamp
        );
    }

    /**
     * Convert to array for template rendering
     */
    public function toArray(): array
    {
        return [
            'activeWorkers' => $this->activeWorkers,
            'totalWorkers' => $this->totalWorkers,
            'jobsInProgress' => $this->jobsInProgress,
            'workerDetails' => $this->workerDetails,
            'lastUpdated' => $this->lastUpdated,
        ];
    }
}
