<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

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

/** 在退出维护模式前由全新 CLI 进程验证运行时与数据库迁移状态。 */
final class HostSystemUpdatePostUpdateHealthCheckService
{
    public const RESULT_PREFIX = 'DBERP_UPDATE_HEALTH_RESULT=';

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

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

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

        $this->executionLogger->logStepCompleted(
            $execution,
            'post_update_health_check',
            (string) __('dberp.system_update.post_apply.log.health_check_completed'),
            $result->toLogContext(),
            now()->utc(),
        );
    }
}
