<?php

declare(strict_types=1);

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');
    }
}
