<?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\HostSystemUpdatePostApplyException;
use Symfony\Component\Process\Process;

/**
 * 通过 Symfony Process 执行白名单 Artisan 命令。
 */
final class ProcessHostSystemUpdateArtisanCommandHandler implements HostSystemUpdateArtisanCommandHandler
{
    public function __construct(
        private readonly PhpCliBinaryResolver $phpCliBinaryResolver,
    ) {}

    public function execute(string $command, array $arguments, ?int $timeoutSeconds): HostSystemUpdateArtisanCommandResult
    {
        if (! function_exists('proc_open')) {
            throw HostSystemUpdatePostApplyException::commandUnavailable($command);
        }

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

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

        $startedAt = now()->utc();
        $startedMicro = microtime(true);

        $processArguments = array_merge(
            [$phpBinary, base_path('artisan'), $command],
            $arguments,
        );

        $process = new Process($processArguments, base_path(), null, null, $timeoutSeconds);
        $process->run();

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

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