<?php

declare(strict_types=1);

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 HostSystemUpdateCacheCleaner $cacheCleaner,
        private readonly HostSystemUpdateVersionWriter $versionWriter,
        private readonly HostSystemUpdateCheckSnapshotAfterUpdateService $checkSnapshotAfterUpdateService,
        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);

        return $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->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],
            );
        }
    }
}
