<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

use App\Exceptions\SupportCenter\HostSystemUpdatePostApplyException;
use App\Models\HostSystemUpdateExecution;

/** 在全新 PHP CLI 进程中验证迁移前运行时，避免读取旧进程的 Composer 静态状态。 */
final class HostSystemUpdateRuntimeReadinessProcessService
{
    public const RESULT_PREFIX = 'DBERP_UPDATE_RUNTIME_RESULT=';

    public function __construct(
        private readonly ProcessHostSystemUpdateArtisanCommandHandler $processHandler,
    ) {}

    public function check(HostSystemUpdateExecution $execution): void
    {
        $result = $this->processHandler->execute(
            'dberp:update-health',
            [
                '--execution='.(string) $execution->execution_no,
                '--runtime-only',
            ],
            120,
        );

        if (! $result->succeeded() || ! str_contains($result->stdout, self::RESULT_PREFIX)) {
            throw HostSystemUpdatePostApplyException::runtimeReadinessFailed('fresh_process_runtime_check_failed');
        }
    }
}
