<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

use App\Enums\SupportCenter\HostSystemUpdateStepPhase;
use App\Models\HostSystemUpdateExecution;

/**
 * 重阶段分批执行编排入口。
 */
final class HostSystemUpdateBatchPhaseRunner
{
    public function __construct(
        private readonly HostSystemUpdateExtractBatchRunner $extractBatchRunner,
        private readonly HostSystemUpdateBackupBatchRunner $backupBatchRunner,
        private readonly HostSystemUpdateFileReplaceBatchRunner $fileReplaceBatchRunner,
        private readonly HostSystemUpdateVendorReplaceBatchRunner $vendorReplaceBatchRunner,
        private readonly HostSystemUpdateExecutionBatchProgressStore $progressStore,
    ) {}

    public function runNextBatch(
        HostSystemUpdateExecution $execution,
        HostSystemUpdateStepPhase $phase,
    ): HostSystemUpdateBatchPhaseResult {
        $execution = $execution->fresh(['package', 'backups']) ?? $execution;

        $result = match ($phase) {
            HostSystemUpdateStepPhase::ExtractStaging => $this->extractBatchRunner->runNextBatch($execution),
            HostSystemUpdateStepPhase::Backup => $this->backupBatchRunner->runNextBatch($execution),
            HostSystemUpdateStepPhase::ReplaceFiles => $this->fileReplaceBatchRunner->runNextBatch($execution),
            HostSystemUpdateStepPhase::ReplaceVendor => $this->vendorReplaceBatchRunner->runNextBatch($execution),
            default => throw new \InvalidArgumentException('Unsupported batch phase.'),
        };

        $this->progressStore->save((string) $execution->execution_no, $result->progress);

        return $result;
    }

    public function isPhaseComplete(HostSystemUpdateExecution $execution, HostSystemUpdateStepPhase $phase): bool
    {
        $progress = $this->snapshotProgress($execution, $phase);

        return $progress?->isCompleted() === true;
    }

    public function snapshotProgress(
        HostSystemUpdateExecution $execution,
        HostSystemUpdateStepPhase $phase,
    ): ?HostSystemUpdateBatchProgress {
        return match ($phase) {
            HostSystemUpdateStepPhase::ExtractStaging => $this->extractBatchRunner->snapshotProgress($execution),
            HostSystemUpdateStepPhase::Backup => $this->backupBatchRunner->snapshotProgress($execution),
            HostSystemUpdateStepPhase::ReplaceFiles => $this->fileReplaceBatchRunner->snapshotProgress($execution),
            HostSystemUpdateStepPhase::ReplaceVendor => $this->vendorReplaceBatchRunner->snapshotProgress($execution),
            default => null,
        };
    }

    public function clearPhaseProgress(HostSystemUpdateExecution $execution, HostSystemUpdateStepPhase $phase): void
    {
        $this->progressStore->clear((string) $execution->execution_no, $phase->value);
    }
}
