<?php
declare(strict_types=1);

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

final class WorkerQuarantineRecord
{
    public const ACTIVE = 'active';
    public const RELEASED = 'released';

    public function __construct(
        private readonly string $workerId,
        private readonly string $reason = '',
        private readonly string $classification = '',
        private readonly string $sourceAction = '',
        private readonly string $status = self::ACTIVE,
        private readonly string $quarantinedAt = '',
        private readonly string $releasedAt = ''
    ) {}

    public static function active(string $workerId, string $reason = '', string $classification = '', string $sourceAction = ''): self
    {
        return new self($workerId, $reason, $classification, $sourceAction, self::ACTIVE, date('c'));
    }

    public static function fromRecoveryAction(array $action): self
    {
        return self::active(
            (string) ($action['workerId'] ?? ''),
            (string) ($action['reason'] ?? 'recovery quarantine candidate'),
            (string) ($action['classification'] ?? ''),
            (string) ($action['action'] ?? '')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['workerId'] ?? ''),
            (string) ($data['reason'] ?? ''),
            (string) ($data['classification'] ?? ''),
            (string) ($data['sourceAction'] ?? ''),
            (string) ($data['status'] ?? self::ACTIVE),
            (string) ($data['quarantinedAt'] ?? ''),
            (string) ($data['releasedAt'] ?? '')
        );
    }

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

    public function isActive(): bool
    {
        return $this->status === self::ACTIVE;
    }

    public function release(): self
    {
        return new self(
            $this->workerId,
            $this->reason,
            $this->classification,
            $this->sourceAction,
            self::RELEASED,
            $this->quarantinedAt,
            date('c')
        );
    }

    public function toArray(): array
    {
        return [
            'workerId' => $this->workerId,
            'reason' => $this->reason,
            'classification' => $this->classification,
            'sourceAction' => $this->sourceAction,
            'status' => $this->status,
            'active' => $this->isActive(),
            'quarantinedAt' => $this->quarantinedAt !== '' ? $this->quarantinedAt : date('c'),
            'releasedAt' => $this->releasedAt,
        ];
    }
}
