import { useState } from "react"; import { open } from "@tauri-apps/plugin-dialog"; import { AlertCircle, AlertTriangle, ArrowRight, CheckCircle2, Database, FileCheck, FolderOpen, Loader2, RotateCcw, Server, Shield, ShieldCheck, Users, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { api, type ConflictResolutionPolicy, type MigrationExecutionReport, type MigrationPlan, type MigrationScope, type SourceInspectionReport, } from "@/lib/api"; import { cn } from "@/lib/utils"; export interface ServerMigrationWizardProps { currentRealmId: string; onClose?: () => void; onSuccess?: () => void; } type WizardStep = "source" | "inspect" | "scope" | "plan" | "executing" | "result"; export function ServerMigrationWizard({ currentRealmId, onClose, onSuccess, }: ServerMigrationWizardProps) { const locale = "ru"; const [step, setStep] = useState("source"); const [sourcePath, setSourcePath] = useState(""); const [inspecting, setInspecting] = useState(false); const [report, setReport] = useState(null); // Scope const [scope, setScope] = useState({ accounts_and_characters: true, module_owned_data: true, server_configuration: true, selected_modules: [], }); // Conflict policy const [conflictPolicy, setConflictPolicy] = useState( "remap_colliding_guids" ); // Plan & Execution const [planning, setPlanning] = useState(false); const [plan, setPlan] = useState(null); const [executing, setExecuting] = useState(false); const [execReport, setExecReport] = useState(null); const [errorMsg, setErrorMsg] = useState(null); async function handlePickSource() { setErrorMsg(null); try { const selected = await open({ directory: true, multiple: false, title: locale === "ru" ? "Выберите каталог исходного сервера" : "Select Source Server Directory", }); if (typeof selected === "string") { setSourcePath(selected); } } catch (e) { setErrorMsg(String(e)); } } async function handleInspect() { if (!sourcePath.trim()) return; setErrorMsg(null); setInspecting(true); try { const res = await api.previewMigrationInspect(sourcePath); setReport(res); // Auto-select detected modules setScope((prev) => ({ ...prev, selected_modules: res.detected_modules.map((m) => m.id), })); setStep("inspect"); } catch (e: any) { setErrorMsg(e?.human?.message || e?.technical || String(e)); } finally { setInspecting(false); } } async function handleCreatePlan() { if (!report) return; setErrorMsg(null); setPlanning(true); try { const res = await api.previewMigrationPlan(sourcePath, currentRealmId, scope, conflictPolicy); setPlan(res); setStep("plan"); } catch (e: any) { setErrorMsg(e?.human?.message || e?.technical || String(e)); } finally { setPlanning(false); } } async function handleExecute() { if (!plan) return; setErrorMsg(null); setExecuting(true); setStep("executing"); try { const res = await api.previewMigrationExecute(plan); setExecReport(res); setStep("result"); if (res.success && onSuccess) { onSuccess(); } } catch (e: any) { setErrorMsg(e?.human?.message || e?.technical || String(e)); setStep("plan"); } finally { setExecuting(false); } } return (
{/* Header */}

{locale === "ru" ? "Центр переноса сервера" : "Server Migration Center"} MIGRATION WIZARD

{locale === "ru" ? "Перенос персонажей, аккаунтов, данных модулей и конфигураций в изолированный модульный сервер Preview." : "Migrate characters, accounts, module data and configs into an isolated modular Preview realm."}

{onClose && ( )}
{errorMsg && (

{locale === "ru" ? "Ошибка переноса" : "Migration Error"}

{errorMsg}

)} {/* Stepper Progress */}
1. Исходный сервер 2. Анализ данных 3. Область переноса 4. План и риски 5. Перенос
{/* STEP 1: SELECT SOURCE */} {step === "source" && (

{locale === "ru" ? "Шаг 1: Укажите каталог исходного сервера" : "Step 1: Select Source Server"}

{locale === "ru" ? "Поддерживаются серверы под управлением CoA Server Manager, устаревшие CoA-серверы со встроенными ботами, а также стандартные серверы AzerothCore." : "Supports CSM-managed servers, legacy embedded CoA installations, and standard AzerothCore."}

setSourcePath(e.target.value)} placeholder="C:\games\CoA Server или путь к серверу..." className="flex-1 rounded-md border border-line bg-bg px-3 py-2 text-xs text-ink focus:border-gold focus:outline-none font-mono" />

{locale === "ru" ? "Гарантия безопасности данных" : "Safety Guarantee"}

{locale === "ru" ? "Анализ выполняется строго в режиме чтения (Read-Only). Никакие скрипты и изменения на исходном сервере не выполняются." : "Source server inspection is strictly read-only. No scripts or writes are performed."}

)} {/* STEP 2: INSPECTION REPORT */} {step === "inspect" && report && (

{locale === "ru" ? "Шаг 2: Результаты анализа исходного сервера" : "Step 2: Source Inspection Results"}

{locale === "ru" ? "Тип сервера" : "Server Type"}

{report.source_type === "CSM_MANAGED_COA" && "CSM Managed CoA"} {report.source_type === "LEGACY_EMBEDDED_COA" && "Legacy CoA (Embedded)"} {report.source_type === "STANDARD_AZEROTH_CORE" && "Standard AzerothCore"} {report.source_type === "UNKNOWN_CUSTOM" && "Custom Layout"}

{locale === "ru" ? "Аккаунтов" : "Accounts"}

{report.accounts_count}

{locale === "ru" ? "Персонажей" : "Characters"}

{report.characters_count}

{locale === "ru" ? "Схема БД" : "DB Schema"}

{report.schema_version ?? "2026_10_28_00"}

{/* Detected Modules */}

{locale === "ru" ? "Обнаруженные модули и таблицы:" : "Detected Modules & Tables:"}

{report.detected_modules.length === 0 ? (

{locale === "ru" ? "Сторонние модули не обнаружены." : "No external modules detected."}

) : (
{report.detected_modules.map((m) => (

{m.name} ({m.id})

Обнаружен через: {m.detected_via}

✓ Адаптер готов
))}
)}
)} {/* STEP 3: SCOPE & CONFLICT RESOLUTION */} {step === "scope" && report && (

{locale === "ru" ? "Шаг 3: Выбор категорий данных и политика конфликтов" : "Step 3: Migration Scope"}

{/* Conflict Policy */}

{locale === "ru" ? "Политика разрешения конфликтов GUID:" : "GUID Conflict Resolution Policy:"}

)} {/* STEP 4: PLAN & RISKS */} {step === "plan" && plan && (

{locale === "ru" ? "Шаг 4: План переноса и подтверждение" : "Step 4: Preflight Plan"}

{locale === "ru" ? "Автоматическое создание точки восстановления" : "Automatic Restore Point"}

{locale === "ru" ? "Перед началом переноса будет создана полная резервная копия целевой базы данных и файлов. В случае любой ошибки состояние будет полностью восстановлено." : "A complete backup of the destination realm will be created before any changes. Full rollback is guaranteed on failure."}

{plan.warnings.length > 0 && (

{locale === "ru" ? "Предупреждения и риски:" : "Warnings:"}

    {plan.warnings.map((w, idx) => (
  • {w}
  • ))}
)}

{locale === "ru" ? "Таблицы к переносу (" + plan.tables_to_migrate.length + "):" : "Tables to Migrate:"}

{plan.tables_to_migrate.map((t) => ( {t} ))}
)} {/* STEP 5: EXECUTING */} {step === "executing" && (

{locale === "ru" ? "Выполняется перенос сервера..." : "Migrating Server Data..."}

{locale === "ru" ? "Создание резервной копии, перенос персонажей, адаптация таблиц модулей и проверка ссылочной целостности." : "Creating backup, remapping character GUIDs, executing module adapters, and verifying integrity."}

)} {/* STEP 6: RESULT */} {step === "result" && execReport && (

{locale === "ru" ? "Перенос сервера успешно завершен!" : "Migration Completed Successfully!"}

{locale === "ru" ? `Все выбранные данные перенесены за ${(execReport.duration_ms / 1000).toFixed(1)} с.` : `All data migrated in ${(execReport.duration_ms / 1000).toFixed(1)}s.`}

Аккаунтов

{execReport.accounts_transferred}

Персонажей

{execReport.characters_transferred}

Модулей адаптировано

{execReport.modules_migrated.length}

Таблиц перенесено

{execReport.tables_migrated.length}

{execReport.backup_path && (

{locale === "ru" ? "Точка восстановления:" : "Restore Point:"}

{execReport.backup_path}

)}
)}
); }