<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

use App\Exceptions\SupportCenter\HostSystemUpdateManifestException;
use App\Exceptions\SupportCenter\SupportCenterException;
use App\Models\HostSystemUpdateExecution;
use App\Models\HostSystemUpdatePackage;
use DomainException;

/**
 * 一键系统更新：检查 → 下载校验 → 解析更新说明 → 创建任务 → 执行更新（不向 UI 暴露分步操作）。
 *
 * Web 管理端默认经 {@see HostSystemUpdateStepRunner} 分步执行；{@see run()} 保留供同步/测试链路的整链调用。
 */
final class HostSystemUpdateOneClickOrchestrator
{
    public function __construct(
        private readonly HostSystemUpdateExecutionLock $executionLock,
        private readonly HostSystemUpdateEntitlementGate $entitlementGate,
        private readonly HostSystemUpdateCheckService $checkService,
        private readonly HostSystemUpdatePackageDownloadService $downloadService,
        private readonly HostSystemUpdateManifestParseService $manifestParseService,
        private readonly HostSystemUpdateExecutionCreateService $executionCreateService,
        private readonly HostSystemUpdateStepRunner $stepRunner,
    ) {}

    public function beginSteppedUpdate(): string
    {
        return $this->stepRunner->beginSession();
    }

    public function run(): HostSystemUpdateExecution
    {
        $sessionId = $this->beginSteppedUpdate();

        while (true) {
            $result = $this->stepRunner->runNextStep($sessionId);

            if ($result->terminal) {
                if ($result->execution instanceof HostSystemUpdateExecution) {
                    return $result->execution;
                }

                throw new DomainException($result->userMessage
                    ?? (string) __('dberp.system_update_center.notifications.update_now_failed_body'));
            }
        }
    }

    /**
     * @deprecated 同步整链准备；Web 分步请使用 {@see HostSystemUpdateStepRunner}
     */
    public function preparePackageAndExecution(): HostSystemUpdateExecution
    {
        $this->assertCanRun();

        $check = $this->checkService->check();

        if (! $check->update_available) {
            throw new DomainException((string) __('dberp.system_update_center.errors.no_update_available'));
        }

        $package = $this->downloadService->downloadAndVerify($check);

        if (! $package->verified) {
            throw new DomainException((string) ($package->download_message
                ?? __('dberp.system_update.package.verification_checksum_mismatch')));
        }

        try {
            $this->manifestParseService->parse($package->fresh() ?? $package);
        } catch (HostSystemUpdateManifestException $exception) {
            throw SupportCenterException::fromFailureEnvelope(
                envelope: [
                    'success' => false,
                    'message' => $exception->userFacingMessage(),
                    'error_code' => $exception->errorCode(),
                ],
                operation: 'host_system_update_one_click',
            );
        }

        $package = $package->fresh() ?? $package;

        if ($package->manifest_status !== HostSystemUpdatePackage::MANIFEST_STATUS_VALID) {
            throw new DomainException((string) __('dberp.system_update_center.errors.package_not_ready'));
        }

        return $this->executionCreateService->create($package);
    }

    public function assertCanRun(): void
    {
        $this->stepRunner->assertCanBegin();
    }
}
