<?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;
use App\Support\DberpMaintenanceDownCommandOptions;
use Symfony\Component\Process\Process;

/**
 * 通过 Symfony Process 执行 artisan down/up。
 */
final class ProcessHostSystemUpdateMaintenanceCommandHandler implements HostSystemUpdateMaintenanceCommandHandler
{
    public function __construct(
        private readonly DberpMaintenanceDownCommandOptions $maintenanceDownOptions,
        private readonly PhpCliBinaryResolver $phpCliBinaryResolver,
    ) {}

    public function executeDown(?int $timeoutSeconds): HostSystemUpdateArtisanCommandResult
    {
        return $this->execute('down', $timeoutSeconds, $this->maintenanceDownOptions->processArgvSuffix());
    }

    public function executeUp(?int $timeoutSeconds): HostSystemUpdateArtisanCommandResult
    {
        return $this->execute('up', $timeoutSeconds);
    }

    /**
     * @param  list<string>  $extraArgv
     */
    private function execute(string $command, ?int $timeoutSeconds, array $extraArgv = []): HostSystemUpdateArtisanCommandResult
    {
        if (! function_exists('proc_open')) {
            throw HostSystemUpdateRecoveryException::maintenanceCommandFailed($command, 1);
        }

        $phpBinary = $this->phpCliBinaryResolver->resolveForProcessExecution();

        if ($phpBinary === null) {
            throw HostSystemUpdateRecoveryException::phpCliUnavailable($command);
        }

        $startedAt = now()->utc();
        $startedMicro = microtime(true);
        $timeout = $timeoutSeconds ?? max(30, (int) config('dberp.system_update.artisan_timeout_seconds', 300));

        $process = new Process(
            array_merge([$phpBinary, base_path('artisan'), $command], $extraArgv),
            base_path(),
            null,
            null,
            $timeout,
        );
        $process->run();

        $finishedAt = now()->utc();
        $durationMs = max(0, (int) round((microtime(true) - $startedMicro) * 1000));

        $result = new HostSystemUpdateArtisanCommandResult(
            command: $command,
            arguments: [],
            exitCode: $process->getExitCode() ?? 1,
            stdout: HostSystemUpdateArtisanOutputSanitizer::sanitize($process->getOutput()),
            stderr: HostSystemUpdateArtisanOutputSanitizer::sanitize($process->getErrorOutput()),
            startedAt: $startedAt,
            finishedAt: $finishedAt,
            durationMs: $durationMs,
        );

        if (! $result->succeeded()) {
            throw HostSystemUpdateRecoveryException::maintenanceCommandFailed($command, $result->exitCode);
        }

        return $result;
    }
}
