<?php

declare(strict_types=1);

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,
    ) {}

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

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

        $process = new Process(
            array_merge([PHP_BINARY, 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;
    }
}
