<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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::ManualRecoveryRequired) {
            throw HostSystemUpdateCliRunException::manualInterventionRequired(
                (string) $execution->execution_no,
                (string) __('dberp.system_update_center.values.result_manual_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);
        }
    }
}
