<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Services\SupportCenter;

use App\Enums\SupportCenter\HostSystemUpdateExecutionStatus;
use App\Enums\SupportCenter\HostSystemUpdateExecutionStep;
use App\Exceptions\SupportCenter\HostSystemUpdatePostApplyException;
use App\Models\HostSystemUpdateExecution;

/**
 * 编排 migrate、cache clear、version write 并进入 completed（不执行回滚）。
 */
final class HostSystemUpdateFinalizeService
{
    public function __construct(
        private readonly HostSystemUpdateExecutionStateMachine $stateMachine,
        private readonly HostSystemUpdateMigrationRunner $migrationRunner,
        private readonly HostSystemUpdateMigrationStateStore $migrationStateStore,
        private readonly HostSystemUpdateCacheCleaner $cacheCleaner,
        private readonly HostSystemUpdateVersionWriter $versionWriter,
        private readonly HostSystemUpdateCheckSnapshotAfterUpdateService $checkSnapshotAfterUpdateService,
        private readonly HostSystemUpdateWorkspaceCleanupService $workspaceCleanupService,
        private readonly SupportCenterAuditLogger $auditLogger,
    ) {}

    public function finalizeUpdate(HostSystemUpdateExecution $execution): HostSystemUpdateExecution
    {
        return $this->markExecutionCompleted($this->finalizeApplyPhases($execution));
    }

    /**
     * 迁移、清缓存、写版本；退出维护模式后再 {@see markExecutionCompleted}。
     */
    public function finalizeApplyPhases(HostSystemUpdateExecution $execution): HostSystemUpdateExecution
    {
        $execution = $this->advanceToRunMigrationsStep($execution);

        try {
            $this->migrationRunner->runMigrations($execution->fresh(['package']) ?? $execution);
        } catch (HostSystemUpdatePostApplyException $exception) {
            $this->handlePostApplyFailure($execution, $exception, HostSystemUpdateExecutionStep::RunMigrations);

            throw $exception;
        }

        return $this->runWriteVersionPhase($this->runClearCachePhase($execution->fresh(['package', 'backups']) ?? $execution));
    }

    public function advanceToRunMigrationsStep(HostSystemUpdateExecution $execution): HostSystemUpdateExecution
    {
        return $this->stateMachine->advanceStep(
            $execution->fresh(['package', 'backups']) ?? $execution,
            HostSystemUpdateExecutionStep::RunMigrations,
            (string) __('dberp.system_update.post_apply.log.finalize_migrations'),
            progressPercent: 70,
        );
    }

    public function runClearCachePhase(HostSystemUpdateExecution $execution): HostSystemUpdateExecution
    {
        $currentStep = HostSystemUpdateExecutionStep::ClearCache;

        try {
            $execution = $this->stateMachine->advanceStep(
                $execution->fresh() ?? $execution,
                HostSystemUpdateExecutionStep::ClearCache,
                (string) __('dberp.system_update.post_apply.log.finalize_cache'),
                progressPercent: 80,
            );

            $this->cacheCleaner->clearCaches($execution->fresh(['package']) ?? $execution);

            return $execution->fresh(['package']) ?? $execution;
        } catch (HostSystemUpdatePostApplyException $exception) {
            $this->handlePostApplyFailure($execution, $exception, $currentStep);

            throw $exception;
        }
    }

    /**
     * 写入版本号并保持 Running（Web 分步在 maintenance_up 之后再标 Completed）。
     */
    public function runWriteVersionPhase(HostSystemUpdateExecution $execution): HostSystemUpdateExecution
    {
        $currentStep = HostSystemUpdateExecutionStep::WriteVersion;

        try {
            $execution = $this->stateMachine->advanceStep(
                $execution->fresh() ?? $execution,
                HostSystemUpdateExecutionStep::WriteVersion,
                (string) __('dberp.system_update.post_apply.log.finalize_version'),
                progressPercent: 90,
            );

            $this->versionWriter->writeVersion($execution->fresh(['package']) ?? $execution);

            return $execution->fresh(['package', 'backups']) ?? $execution;
        } catch (HostSystemUpdatePostApplyException $exception) {
            $this->handlePostApplyFailure($execution, $exception, $currentStep);

            throw $exception;
        }
    }

    public function markExecutionCompleted(HostSystemUpdateExecution $execution): HostSystemUpdateExecution
    {
        $execution = $this->stateMachine->transition(
            $execution->fresh() ?? $execution,
            HostSystemUpdateExecutionStatus::Completed,
            HostSystemUpdateExecutionStep::Completed,
            (string) __('dberp.system_update.post_apply.log.completed'),
        );

        $fresh = $execution->fresh(['package', 'backups']) ?? $execution;
        $this->checkSnapshotAfterUpdateService->apply($fresh);
        $this->auditLogger->logSystemUpdateExecutionCompleted($fresh);
        $this->workspaceCleanupService->cleanupAfterCompleted($fresh);

        return $fresh->fresh(['package', 'backups']) ?? $fresh;
    }

    public function runWriteVersionAndComplete(HostSystemUpdateExecution $execution): HostSystemUpdateExecution
    {
        return $this->markExecutionCompleted($this->runWriteVersionPhase($execution));
    }

    private function handlePostApplyFailure(
        HostSystemUpdateExecution $execution,
        HostSystemUpdatePostApplyException $exception,
        HostSystemUpdateExecutionStep $currentStep,
    ): void {
        $fresh = $execution->fresh() ?? $execution;

        if ($exception->requiresRollback()
            && $this->migrationStateStore->hasAppliedMigrationsSinceBaseline($fresh)) {
            $this->stateMachine->requireManualRecovery(
                $fresh,
                $exception->errorCode(),
                trim($exception->userFacingMessage().' '.__('dberp.system_update.recovery.database_manual_recovery_required')),
                ['failed_step' => $currentStep->value, 'database_changes_detected' => true],
                $currentStep,
            );
        } elseif ($exception->requiresRollback()) {
            $this->stateMachine->requireRollback(
                $fresh,
                $exception->errorCode(),
                $exception->userFacingMessage(),
                ['failed_step' => $currentStep->value],
                $currentStep,
            );
        } else {
            $this->stateMachine->fail(
                $fresh,
                $exception->errorCode(),
                $exception->userFacingMessage(),
                ['failed_step' => $currentStep->value],
            );
        }
    }
}
