<?php

declare(strict_types=1);

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

namespace App\Services\SupportCenter;

use App\Exceptions\SupportCenter\HostSystemUpdateRecoveryException;

/**
 * 维护模式：优先进程内执行，失败且 proc_open 可用时回退子进程。
 */
final class FallbackHostSystemUpdateMaintenanceCommandHandler implements HostSystemUpdateMaintenanceCommandHandler
{
    public function __construct(
        private readonly HostSystemUpdateMaintenanceCommandHandler $primary,
        private readonly HostSystemUpdateMaintenanceCommandHandler $fallback,
    ) {}

    public function executeDown(?int $timeoutSeconds): HostSystemUpdateArtisanCommandResult
    {
        return $this->executeWithFallback(
            fn (): HostSystemUpdateArtisanCommandResult => $this->primary->executeDown($timeoutSeconds),
            fn (): HostSystemUpdateArtisanCommandResult => $this->fallback->executeDown($timeoutSeconds),
        );
    }

    public function executeUp(?int $timeoutSeconds): HostSystemUpdateArtisanCommandResult
    {
        return $this->executeWithFallback(
            fn (): HostSystemUpdateArtisanCommandResult => $this->primary->executeUp($timeoutSeconds),
            fn (): HostSystemUpdateArtisanCommandResult => $this->fallback->executeUp($timeoutSeconds),
        );
    }

    /**
     * @param  callable(): HostSystemUpdateArtisanCommandResult  $primary
     * @param  callable(): HostSystemUpdateArtisanCommandResult  $fallback
     */
    private function executeWithFallback(callable $primary, callable $fallback): HostSystemUpdateArtisanCommandResult
    {
        try {
            return $primary();
        } catch (HostSystemUpdateRecoveryException $exception) {
            if (! $this->canUseProcessFallback()) {
                throw $exception;
            }

            return $fallback();
        }
    }

    private function canUseProcessFallback(): bool
    {
        return function_exists('proc_open');
    }
}
