<?php
declare(strict_types=1);

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

final class WorkerQuarantinePolicy
{
    public function __construct(
        private readonly bool $quarantineFailed = true,
        private readonly bool $quarantineHung = false,
        private readonly bool $quarantineOffline = false,
        private readonly int $maxQuarantinePerRun = 50
    ) {}

    public static function default(): self
    {
        return new self();
    }

    public function shouldQuarantine(string $classification, string $recoveryAction = ''): bool
    {
        if ($recoveryAction === WorkerRecoveryAction::QUARANTINE_CANDIDATE) {
            return true;
        }

        return match ($classification) {
            WorkerStaleRecord::FAILED => $this->quarantineFailed,
            WorkerStaleRecord::HUNG => $this->quarantineHung,
            WorkerStaleRecord::OFFLINE => $this->quarantineOffline,
            default => false,
        };
    }

    public function maxQuarantinePerRun(): int
    {
        return max(1, $this->maxQuarantinePerRun);
    }

    public function toArray(): array
    {
        return [
            'quarantineFailed' => $this->quarantineFailed,
            'quarantineHung' => $this->quarantineHung,
            'quarantineOffline' => $this->quarantineOffline,
            'maxQuarantinePerRun' => $this->maxQuarantinePerRun(),
        ];
    }
}
