"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useRef, useState } from "react";
import { AlertCircle, CheckCircle, Database, Download, RefreshCw, } from "lucide-react";
import { get, post } from "./services/serviceHelper";
export function MigrationsView({ isAdmin, onMigrationsComplete, }) {
    const [status, setStatus] = useState(null);
    const [loading, setLoading] = useState(true);
    const [running, setRunning] = useState(false);
    const [autoRunning, setAutoRunning] = useState(false);
    const [result, setResult] = useState(null);
    const autoAttemptedRef = useRef(false);
    const displayName = useCallback((name) => {
        return name?.replace(/^Parhelia\.Migrations\./i, "") || name;
    }, []);
    const checkStatus = useCallback(async () => {
        try {
            setLoading(true);
            setResult(null);
            const res = await get("/parhelia/migration-status");
            setStatus(res?.data ?? {
                hasPendingMigrations: false,
                pendingMigrations: [],
                appliedMigrations: [],
                errorMessage: "Empty response from migration-status",
            });
        }
        catch (e) {
            setStatus({
                hasPendingMigrations: false,
                pendingMigrations: [],
                appliedMigrations: [],
                errorMessage: e?.message || "Failed to check migration status",
            });
        }
        finally {
            setLoading(false);
        }
    }, []);
    const runMigrations = useCallback(async (automatic = false) => {
        try {
            setRunning(true);
            setAutoRunning(automatic);
            setResult(null);
            const res = await post("/parhelia/run-migrations", {});
            const nextResult = res?.data ?? {
                success: false,
                errorMessage: res?.details ||
                    res?.summary ||
                    (automatic
                        ? "Automatic migration failed. Please run migrations manually."
                        : "Empty response from run-migrations"),
                executedMigrations: [],
            };
            setResult(nextResult);
            if (nextResult.success) {
                // Refresh status after successful migration
                await checkStatus();
                // If no more pending migrations, notify parent
                const statusRes = await get("/parhelia/migration-status");
                if (!statusRes?.data?.hasPendingMigrations) {
                    onMigrationsComplete();
                }
            }
        }
        catch (e) {
            setResult({
                success: false,
                errorMessage: e?.message ||
                    (automatic
                        ? "Automatic migration failed. Please run migrations manually."
                        : "Failed to run migrations"),
                executedMigrations: [],
            });
        }
        finally {
            setAutoRunning(false);
            setRunning(false);
        }
    }, [checkStatus, onMigrationsComplete]);
    const downloadScript = useCallback(async () => {
        try {
            const response = await fetch("/parhelia/migration-script");
            const script = await response.text();
            // Create blob and download
            const blob = new Blob([script], { type: "text/plain" });
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.href = url;
            link.download = `parhelia-migrations-${new Date().toISOString().split("T")[0]}.sql`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
        }
        catch (e) {
            alert("Failed to download migration script: " +
                (e?.message || "Unknown error"));
        }
    }, []);
    // Initial load: fetch detailed migration status if admin
    useEffect(() => {
        if (isAdmin) {
            checkStatus();
        }
        else {
            setLoading(false);
        }
    }, [isAdmin, checkStatus]);
    // For admins, try one automatic migration run when pending migrations are detected.
    // If it fails, we fall back to the existing manual migration UX.
    useEffect(() => {
        if (!isAdmin || loading || running || autoAttemptedRef.current) {
            return;
        }
        if (status?.hasPendingMigrations) {
            autoAttemptedRef.current = true;
            void runMigrations(true);
        }
    }, [isAdmin, loading, running, runMigrations, status?.hasPendingMigrations]);
    if (loading) {
        return (_jsx("div", { className: "fixed inset-0 flex items-center justify-center bg-gray-50", children: _jsxs("div", { className: "text-center", children: [_jsx(RefreshCw, { className: "mx-auto mb-4 h-8 w-8 animate-spin text-blue-600" }), _jsx("p", { className: "text-gray-600", children: "Checking migration status..." })] }) }));
    }
    // Migration issues exist but user is not admin
    if (!isAdmin) {
        return (_jsx("div", { className: "fixed inset-0 flex items-center justify-center bg-gray-50 p-4", children: _jsxs("div", { className: "w-full max-w-2xl rounded-lg bg-white p-8 shadow-md", children: [_jsxs("div", { className: "mb-4 flex items-center gap-3", children: [_jsx(AlertCircle, { className: "h-8 w-8 text-amber-600" }), _jsx("h1", { className: "text-2xl font-semibold text-gray-900", children: "Maintenance Required" })] }), _jsx("div", { className: "rounded-md border border-amber-200 bg-amber-50 p-4", children: _jsx("p", { className: "text-amber-900", children: "Database maintenance is required before Parhelia can be used. Please contact an administrator." }) })] }) }));
    }
    if (status?.errorMessage) {
        return (_jsx("div", { className: "fixed inset-0 flex items-center justify-center bg-gray-50 p-4", children: _jsxs("div", { className: "w-full max-w-2xl rounded-lg bg-white p-8 shadow-md", children: [_jsxs("div", { className: "mb-4 flex items-center gap-3", children: [_jsx(AlertCircle, { className: "h-8 w-8 text-red-600" }), _jsx("h1", { className: "text-2xl font-semibold text-gray-900", children: "Migration Error" })] }), _jsx("div", { className: "mb-6 rounded-md border border-red-200 bg-red-50 p-4", children: _jsx("p", { className: "whitespace-pre-wrap text-red-800", children: status.errorMessage }) }), _jsxs("button", { onClick: checkStatus, className: "flex items-center gap-2 rounded-md bg-blue-600 px-4 py-2 text-white hover:bg-blue-700", children: [_jsx(RefreshCw, { className: "h-4 w-4" }), "Recheck"] })] }) }));
    }
    if (!status?.hasPendingMigrations) {
        return (_jsx("div", { className: "fixed inset-0 flex items-center justify-center bg-gray-50 p-4", children: _jsxs("div", { className: "w-full max-w-2xl rounded-lg bg-white p-8 shadow-md", children: [_jsxs("div", { className: "mb-4 flex items-center gap-3", children: [_jsx(CheckCircle, { className: "h-8 w-8 text-green-600" }), _jsx("h1", { className: "text-2xl font-semibold text-gray-900", children: "Database Up to Date" })] }), _jsx("p", { className: "mb-6 text-gray-600", children: "All database migrations have been applied successfully." }), _jsxs("div", { className: "flex gap-3", children: [_jsx("button", { onClick: onMigrationsComplete, className: "rounded-md bg-blue-600 px-4 py-2 text-white hover:bg-blue-700", children: "Continue to Parhelia" }), _jsxs("button", { onClick: checkStatus, className: "flex items-center gap-2 rounded-md bg-gray-200 px-4 py-2 text-gray-700 hover:bg-gray-300", children: [_jsx(RefreshCw, { className: "h-4 w-4" }), "Recheck"] })] })] }) }));
    }
    return (_jsx("div", { className: "fixed inset-0 flex items-center justify-center overflow-auto bg-gray-50 p-4", children: _jsxs("div", { className: "my-8 w-full max-w-3xl rounded-lg bg-white p-8 shadow-md", children: [_jsxs("div", { className: "mb-6 flex items-center gap-3", children: [_jsx(Database, { className: "h-8 w-8 text-blue-600" }), _jsx("h1", { className: "text-2xl font-semibold text-gray-900", children: "Parhelia Database Migrations Required" })] }), _jsxs("div", { className: "mb-6 rounded-md border border-amber-200 bg-amber-50 p-4", children: [_jsxs("p", { className: "mb-2 text-amber-900", children: [_jsx("strong", { children: "Important:" }), " The database requires migration before Parhelia can be used."] }), _jsx("p", { className: "text-sm text-amber-800", children: "You can run migrations directly or download the SQL script for manual execution." })] }), _jsxs("div", { className: "mb-6", children: [_jsx("h2", { className: "mb-3 text-lg font-medium text-gray-900", children: "Pending Migrations" }), _jsx("div", { className: "max-h-64 overflow-y-auto rounded-md bg-gray-50 p-4", children: _jsx("ul", { className: "space-y-1", children: status.pendingMigrations.map((migration) => (_jsxs("li", { className: "font-mono text-sm text-gray-700", children: ["\u2022 ", displayName(migration)] }, migration))) }) })] }), result && (_jsxs("div", { className: `mb-6 rounded-md p-4 ${result.success
                        ? "border border-green-200 bg-green-50"
                        : "border border-red-200 bg-red-50"}`, children: [_jsxs("div", { className: "mb-2 flex items-center gap-2", children: [result.success ? (_jsx(CheckCircle, { className: "h-5 w-5 text-green-600" })) : (_jsx(AlertCircle, { className: "h-5 w-5 text-red-600" })), _jsx("h3", { className: `font-medium ${result.success ? "text-green-900" : "text-red-900"}`, children: result.success ? "Migration Successful" : "Migration Failed" })] }), result.errorMessage && (_jsx("p", { className: "text-sm whitespace-pre-wrap text-red-800", children: result.errorMessage })), result.success && result.executedMigrations.length > 0 && (_jsxs("div", { className: "mt-2", children: [_jsx("p", { className: "mb-1 text-sm text-green-800", children: "Executed migrations:" }), _jsx("ul", { className: "text-sm text-green-700", children: result.executedMigrations.map((m) => (_jsxs("li", { className: "font-mono", children: ["\u2022 ", displayName(m)] }, m))) })] }))] })), _jsxs("div", { className: "flex flex-wrap gap-3", children: [_jsx("button", { onClick: () => runMigrations(false), disabled: running, className: "flex items-center gap-2 rounded-md bg-blue-600 px-4 py-2 text-white hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-gray-400", children: running ? (_jsxs(_Fragment, { children: [_jsx(RefreshCw, { className: "h-4 w-4 animate-spin" }), autoRunning
                                        ? "Applying Migrations Automatically..."
                                        : "Running Migrations..."] })) : (_jsxs(_Fragment, { children: [_jsx(Database, { className: "h-4 w-4" }), "Run Migrations"] })) }), _jsxs("button", { onClick: downloadScript, className: "flex items-center gap-2 rounded-md bg-gray-200 px-4 py-2 text-gray-700 hover:bg-gray-300", children: [_jsx(Download, { className: "h-4 w-4" }), "Download Script"] }), _jsxs("button", { onClick: checkStatus, className: "flex items-center gap-2 rounded-md bg-gray-200 px-4 py-2 text-gray-700 hover:bg-gray-300", children: [_jsx(RefreshCw, { className: "h-4 w-4" }), "Recheck"] })] }), status.appliedMigrations.length > 0 && (_jsx("div", { className: "mt-8 border-t border-gray-200 pt-6", children: _jsxs("details", { className: "text-sm", children: [_jsxs("summary", { className: "cursor-pointer text-gray-600 hover:text-gray-900", children: ["View applied migrations (", status.appliedMigrations.length, ")"] }), _jsx("div", { className: "mt-3 max-h-48 overflow-y-auto rounded-md bg-gray-50 p-3", children: _jsx("ul", { className: "space-y-1", children: status.appliedMigrations.map((migration) => (_jsxs("li", { className: "font-mono text-gray-600", children: ["\u2713 ", displayName(migration)] }, migration))) }) })] }) }))] }) }));
}
//# sourceMappingURL=MigrationsView.js.map