<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

use App\Exceptions\SupportCenter\HostSystemUpdatePostApplyException;

/**
 * 缓存清理等 Artisan 白名单命令：优先进程内，失败且 proc_open 可用时回退子进程。
 */
final class FallbackHostSystemUpdateArtisanCommandHandler implements HostSystemUpdateArtisanCommandHandler
{
    public function __construct(
        private readonly HostSystemUpdateArtisanCommandHandler $primary,
        private readonly HostSystemUpdateArtisanCommandHandler $fallback,
    ) {}

    /**
     * @param  list<string>  $arguments
     */
    public function execute(string $command, array $arguments, ?int $timeoutSeconds): HostSystemUpdateArtisanCommandResult
    {
        try {
            $result = $this->primary->execute($command, $arguments, $timeoutSeconds);

            if ($result->succeeded()) {
                return $result;
            }
        } catch (HostSystemUpdatePostApplyException) {
            if (! $this->canUseProcessFallback()) {
                throw HostSystemUpdatePostApplyException::commandFailed($command, 1);
            }

            return $this->fallback->execute($command, $arguments, $timeoutSeconds);
        }

        if ($result->succeeded() || ! $this->canUseProcessFallback()) {
            return $result;
        }

        return $this->fallback->execute($command, $arguments, $timeoutSeconds);
    }

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