"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useState } from "react";
import { AlertCircle, CheckCircle, Database, Download, RefreshCw, } from "lucide-react";
import { get, post } from "./services/serviceHelper";
const manualMigrationSteps = [
    "Download the migration script.",
    "Run the SQL script against the Parhelia database with a database account that can apply schema changes.",
    "Come back to this screen and click Recheck.",
];
export function MigrationsView({ isAdmin, onMigrationsComplete, }) {
    const [status, setStatus] = useState(null);
    const [loading, setLoading] = useState(true);
    const [running, setRunning] = useState(false);
    const [result, setResult] = useState(null);
    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 () => {
        try {
            setRunning(true);
            setResult(null);
            const res = await post("/parhelia/run-migrations", {});
            const nextResult = res?.data ?? {
                success: false,
                errorMessage: res?.details || res?.summary || "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 || "Failed to run migrations",
                executedMigrations: [],
            });
        }
        finally {
            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]);
    if (loading) {
        return (_jsx("div", { className: "bg-neutral-grey-5 fixed inset-0 flex items-center justify-center", children: _jsxs("div", { className: "text-center", children: [_jsx(RefreshCw, { className: "text-feedback-blue mx-auto mb-4 h-8 w-8 animate-spin" }), _jsx("p", { className: "text-neutral-grey-50", children: "Checking migration status..." })] }) }));
    }
    // Migration issues exist but user is not admin
    if (!isAdmin) {
        return (_jsx("div", { className: "bg-neutral-grey-5 fixed inset-0 flex items-center justify-center 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: "text-feedback-orange h-8 w-8" }), _jsx("h1", { className: "text-neutral-grey-100 text-2xl font-medium", children: "Maintenance Required" })] }), _jsx("div", { className: "border-feedback-orange bg-feedback-orange-light rounded-md border p-4", children: _jsx("p", { className: "text-feedback-orange", children: "Database maintenance is required before Parhelia can be used. Please contact an administrator." }) })] }) }));
    }
    if (status?.errorMessage) {
        return (_jsx("div", { className: "bg-neutral-grey-5 fixed inset-0 flex items-center justify-center 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: "text-feedback-red h-8 w-8" }), _jsx("h1", { className: "text-neutral-grey-100 text-2xl font-medium", children: "Migration Error" })] }), _jsx("div", { className: "border-feedback-red bg-feedback-red-light mb-6 rounded-md border p-4", children: _jsx("p", { className: "text-feedback-red whitespace-pre-wrap", children: status.errorMessage }) }), _jsxs("button", { onClick: checkStatus, className: "bg-feedback-blue hover:bg-feedback-blue flex items-center gap-2 rounded-md px-4 py-2 text-white", children: [_jsx(RefreshCw, { className: "h-4 w-4" }), "Recheck"] })] }) }));
    }
    if (!status?.hasPendingMigrations) {
        return (_jsx("div", { className: "bg-neutral-grey-5 fixed inset-0 flex items-center justify-center 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: "text-feedback-green h-8 w-8" }), _jsx("h1", { className: "text-neutral-grey-100 text-2xl font-medium", children: "Database Up to Date" })] }), _jsx("p", { className: "text-neutral-grey-50 mb-6", children: "All database migrations have been applied successfully." }), _jsxs("div", { className: "flex gap-3", children: [_jsx("button", { onClick: onMigrationsComplete, className: "bg-feedback-blue hover:bg-feedback-blue rounded-md px-4 py-2 text-white", children: "Continue to Parhelia" }), _jsxs("button", { onClick: checkStatus, className: "bg-neutral-grey-10 text-neutral-grey-100 hover:bg-neutral-grey-10 flex items-center gap-2 rounded-md px-4 py-2", children: [_jsx(RefreshCw, { className: "h-4 w-4" }), "Recheck"] })] })] }) }));
    }
    return (_jsx("div", { className: "bg-neutral-grey-5 fixed inset-0 flex items-center justify-center overflow-auto 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: "text-feedback-blue h-8 w-8" }), _jsx("h1", { className: "text-neutral-grey-100 text-2xl font-medium", children: "Parhelia Database Migrations Required" })] }), _jsxs("div", { className: "border-feedback-orange bg-feedback-orange-light mb-6 rounded-md border p-4", children: [_jsxs("p", { className: "text-feedback-orange mb-2", children: [_jsx("strong", { children: "Important:" }), " The database requires migration before Parhelia can be used."] }), _jsx("p", { className: "text-feedback-orange text-sm", children: "You can run migrations directly or download the SQL script for manual execution. If running migrations fails because the SQL account is missing schema permissions, download the script, run it on the database, then recheck this screen." })] }), _jsxs("div", { className: "mb-6", children: [_jsx("h2", { className: "text-neutral-grey-100 mb-3 text-lg font-medium", children: "Pending Migrations" }), _jsx("div", { className: "bg-neutral-grey-5 max-h-64 overflow-y-auto rounded-md p-4", children: _jsx("ul", { className: "space-y-1", children: status.pendingMigrations.map((migration) => (_jsxs("li", { className: "text-neutral-grey-100 font-mono text-sm", children: ["\u2022 ", displayName(migration)] }, migration))) }) })] }), result && (_jsxs("div", { className: `mb-6 rounded-md p-4 ${result.success
                        ? "border-feedback-green bg-feedback-green-light border"
                        : "border-feedback-red bg-feedback-red-light border"}`, children: [_jsxs("div", { className: "mb-2 flex items-center gap-2", children: [result.success ? (_jsx(CheckCircle, { className: "text-feedback-green h-5 w-5" })) : (_jsx(AlertCircle, { className: "text-feedback-red h-5 w-5" })), _jsx("h3", { className: `font-medium ${result.success ? "text-feedback-green" : "text-feedback-red"}`, children: result.success ? "Migration Successful" : "Migration Failed" })] }), result.errorMessage && (_jsx("p", { className: "text-feedback-red text-sm whitespace-pre-wrap", children: result.errorMessage })), !result.success && (_jsxs("div", { className: "border-feedback-red mt-3 rounded-md border bg-white/70 p-3", children: [_jsx("p", { className: "text-feedback-red mb-2 text-sm font-medium", children: "Manual migration path:" }), _jsx("ol", { className: "text-feedback-red list-decimal space-y-1 pl-5 text-sm", children: manualMigrationSteps.map((step) => (_jsx("li", { children: step }, step))) })] })), result.success && result.executedMigrations.length > 0 && (_jsxs("div", { className: "mt-2", children: [_jsx("p", { className: "text-feedback-green mb-1 text-sm", children: "Executed migrations:" }), _jsx("ul", { className: "text-feedback-green text-sm", 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(), disabled: running, className: "bg-feedback-blue hover:bg-feedback-blue disabled:bg-neutral-grey-50 flex items-center gap-2 rounded-md px-4 py-2 text-white disabled:cursor-not-allowed", children: running ? (_jsxs(_Fragment, { children: [_jsx(RefreshCw, { className: "h-4 w-4 animate-spin" }), "Running Migrations..."] })) : (_jsxs(_Fragment, { children: [_jsx(Database, { className: "h-4 w-4" }), "Run Migrations"] })) }), _jsxs("button", { onClick: downloadScript, className: "bg-neutral-grey-10 text-neutral-grey-100 hover:bg-neutral-grey-10 flex items-center gap-2 rounded-md px-4 py-2", children: [_jsx(Download, { className: "h-4 w-4" }), "Download Script"] }), _jsxs("button", { onClick: checkStatus, className: "bg-neutral-grey-10 text-neutral-grey-100 hover:bg-neutral-grey-10 flex items-center gap-2 rounded-md px-4 py-2", children: [_jsx(RefreshCw, { className: "h-4 w-4" }), "Recheck"] })] }), status.appliedMigrations.length > 0 && (_jsx("div", { className: "border-border-default mt-8 border-t pt-6", children: _jsxs("details", { className: "text-sm", children: [_jsxs("summary", { className: "text-neutral-grey-50 hover:text-neutral-grey-100 cursor-pointer", children: ["View applied migrations (", status.appliedMigrations.length, ")"] }), _jsx("div", { className: "bg-neutral-grey-5 mt-3 max-h-48 overflow-y-auto rounded-md p-3", children: _jsx("ul", { className: "space-y-1", children: status.appliedMigrations.map((migration) => (_jsxs("li", { className: "text-neutral-grey-50 font-mono", children: ["\u2713 ", displayName(migration)] }, migration))) }) })] }) }))] }) }));
}
//# sourceMappingURL=MigrationsView.js.map