<?php
declare(strict_types=1);

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

final class WorkerRecoveryAction
{
    public const RESTART = 'restart';
    public const REHYDRATE = 'rehydrate';
    public const REALLOCATE = 'reallocate';
    public const QUARANTINE_CANDIDATE = 'quarantine_candidate';
    public const SKIP = 'skip';

    public function __construct(
        private readonly string $workerId,
        private readonly string $action,
        private readonly string $reason = '',
        private readonly string $classification = '',
        private readonly bool $successful = true,
        private readonly string $performedAt = ''
    ) {}

    public static function forClassification(string $workerId, string $classification): self
    {
        return match ($classification) {
            WorkerStaleRecord::STALE => new self($workerId, self::REHYDRATE, 'stale worker rehydrated', $classification, true, date('c')),
            WorkerStaleRecord::HUNG => new self($workerId, self::RESTART, 'hung worker restarted', $classification, true, date('c')),
            WorkerStaleRecord::OFFLINE => new self($workerId, self::REALLOCATE, 'offline worker jobs reallocated', $classification, true, date('c')),
            WorkerStaleRecord::FAILED => new self($workerId, self::QUARANTINE_CANDIDATE, 'failed worker marked for quarantine', $classification, true, date('c')),
            default => new self($workerId, self::SKIP, 'worker healthy', $classification, true, date('c')),
        };
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['workerId'] ?? ''),
            (string) ($data['action'] ?? self::SKIP),
            (string) ($data['reason'] ?? ''),
            (string) ($data['classification'] ?? ''),
            (bool) ($data['successful'] ?? true),
            (string) ($data['performedAt'] ?? '')
        );
    }

    public function workerId(): string { return $this->workerId; }
    public function action(): string { return $this->action; }
    public function successful(): bool { return $this->successful; }

    public function toArray(): array
    {
        return [
            'workerId' => $this->workerId,
            'action' => $this->action,
            'reason' => $this->reason,
            'classification' => $this->classification,
            'successful' => $this->successful,
            'performedAt' => $this->performedAt !== '' ? $this->performedAt : date('c'),
        ];
    }
}
