<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

use App\Enums\SupportCenter\HostSystemUpdateExecutionStatus;
use App\Models\HostSystemUpdateExecution;

/**
 * CLI 执行任务前置策略（锁、终态、权益）。
 */
final class HostSystemUpdateCliExecutionPolicy
{
    public function __construct(
        private readonly HostSystemUpdateExecutionLock $executionLock,
        private readonly HostSystemUpdateEntitlementGate $entitlementGate,
        private readonly HostSystemUpdateStatusPresenter $statusPresenter,
    ) {}

    public function assertRunnable(HostSystemUpdateExecution $execution): void
    {
        if (! $this->entitlementGate->canExecuteUpdate()) {
            throw HostSystemUpdateCliRunException::entitlementDenied($this->entitlementGate->executeReason());
        }

        $status = HostSystemUpdateExecutionStatus::tryFrom((string) ($execution->status ?? ''));

        if ($status === null) {
            throw HostSystemUpdateCliRunException::notRetryable(
                (string) $execution->execution_no,
                (string) __('dberp.system_update_center.values.result_unknown'),
            );
        }

        if ($status === HostSystemUpdateExecutionStatus::Completed) {
            throw HostSystemUpdateCliRunException::alreadyCompleted((string) $execution->execution_no);
        }

        if (in_array($status, [
            HostSystemUpdateExecutionStatus::Failed,
            HostSystemUpdateExecutionStatus::Cancelled,
            HostSystemUpdateExecutionStatus::RolledBack,
            HostSystemUpdateExecutionStatus::RollbackFailed,
        ], true)) {
            throw HostSystemUpdateCliRunException::notRetryable(
                (string) $execution->execution_no,
                $this->statusPresenter->label($status->value),
            );
        }

        if ($status === HostSystemUpdateExecutionStatus::RollbackRequired) {
            throw HostSystemUpdateCliRunException::manualInterventionRequired(
                (string) $execution->execution_no,
                (string) __('dberp.system_update_center.values.result_needs_recovery'),
            );
        }

        if ($status === HostSystemUpdateExecutionStatus::RollingBack) {
            throw HostSystemUpdateCliRunException::manualInterventionRequired(
                (string) $execution->execution_no,
                (string) __('dberp.system_update_center.values.result_recovering'),
            );
        }

        $active = $this->executionLock->findActiveExecution();

        if ($active instanceof HostSystemUpdateExecution
            && (string) $active->execution_no !== (string) $execution->execution_no) {
            throw HostSystemUpdateCliRunException::anotherExecutionActive((string) $active->execution_no);
        }
    }
}
