<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

use App\Exceptions\SupportCenter\HostSystemUpdatePostApplyException;
use Symfony\Component\Process\Process;

/**
 * 通过 Symfony Process 执行白名单 Artisan 命令。
 */
final class ProcessHostSystemUpdateArtisanCommandHandler implements HostSystemUpdateArtisanCommandHandler
{
    public function execute(string $command, array $arguments, ?int $timeoutSeconds): HostSystemUpdateArtisanCommandResult
    {
        if (! function_exists('proc_open')) {
            throw HostSystemUpdatePostApplyException::commandUnavailable($command);
        }

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

        $processArguments = array_merge(
            [PHP_BINARY, 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,
        );
    }
}
