import { jsx as _jsx } from "react/jsx-runtime";
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { act, cleanup, render, waitFor } from '@testing-library/react';
let latestDashboardProps = null;
const fetchToolsMock = vi.fn(async () => { });
const listPromptsMock = vi.fn();
const refetchMock = vi.fn(() => Promise.resolve());
const callToolMock = vi.fn();
const abortMock = vi.fn();
vi.mock('../../hooks/useLocalStorage', async () => {
    const React = await import('react');
    const useLocalStorage = (key, initialValue) => {
        const [storedValue, setStoredValue] = React.useState(initialValue);
        const setValue = React.useCallback((value) => {
            setStoredValue((prev) => (value instanceof Function ? value(prev) : value));
        }, []);
        const removeValue = React.useCallback(() => {
            setStoredValue(initialValue);
        }, [initialValue]);
        return [storedValue, setValue, removeValue];
    };
    const useLocalStorageState = (key, initialValue) => {
        const [value, setValue] = React.useState(initialValue);
        const update = React.useCallback((updater) => {
            setValue((prev) => updater(prev));
        }, []);
        const setValueDirect = React.useCallback((next) => {
            setValue(next);
        }, []);
        const reset = React.useCallback(() => {
            setValue(initialValue);
        }, [initialValue]);
        const removeValue = React.useCallback(() => {
            setValue(initialValue);
        }, [initialValue]);
        return {
            value,
            setValue: setValueDirect,
            update,
            reset,
            removeValue
        };
    };
    return {
        useLocalStorage,
        useLocalStorageState
    };
});
vi.mock('react-mcp-hook', () => ({
    useMcp: vi.fn(() => ({
        fetchTools: fetchToolsMock,
        callTool: callToolMock,
        refetch: refetchMock,
        tools: [],
        error: undefined,
        abort: abortMock,
        loading: false,
        serverInfo: undefined,
        protocolVersion: undefined,
        capabilities: undefined,
        lastEvent: undefined,
        listPrompts: listPromptsMock,
        getPrompt: undefined
    }))
}));
vi.mock('../ServerSetupView', () => ({
    __esModule: true,
    default: () => null
}));
vi.mock('../ServerCheckingView', () => ({
    __esModule: true,
    default: () => null
}));
vi.mock('../ServerErrorView', () => ({
    __esModule: true,
    default: () => null
}));
vi.mock('../ToolRunnerView', () => ({
    __esModule: true,
    default: () => null
}));
vi.mock('../ServerDashboardView', () => ({
    __esModule: true,
    default: (props) => {
        latestDashboardProps = props;
        return _jsx("div", { "data-testid": 'server-dashboard-view' });
    }
}));
import { McpServersProvider } from '../../contexts/McpContext';
import McpServer from '../McpServer';
const initialPrompt = {
    name: 'cached-prompt',
    description: 'Cached prompt description',
    arguments: []
};
const firstFetchedPrompt = {
    name: 'fresh-prompt-1',
    description: 'First fetched prompt',
    arguments: []
};
const secondFetchedPrompt = {
    name: 'fresh-prompt-2',
    description: 'Second fetched prompt',
    arguments: []
};
describe('McpServer prompt cache revalidation', () => {
    beforeEach(() => {
        latestDashboardProps = null;
        fetchToolsMock.mockClear();
        listPromptsMock.mockReset();
        let fetchCount = 0;
        listPromptsMock.mockImplementation(() => {
            const prompt = fetchCount === 0 ? firstFetchedPrompt : secondFetchedPrompt;
            fetchCount += 1;
            return Promise.resolve({ prompts: [prompt], nextCursor: undefined });
        });
        refetchMock.mockClear();
        callToolMock.mockClear();
        abortMock.mockClear();
    });
    afterEach(() => {
        cleanup();
    });
    it('clears cached prompts when disabled and refetches when re-enabled', async () => {
        const initialServers = [
            {
                id: 'server-1',
                options: {
                    url: 'https://example.com/mcp',
                    serverName: 'Example Server',
                    serverEnabled: true,
                    cachedPrompts: [initialPrompt],
                    headers: {}
                }
            }
        ];
        render(_jsx(McpServersProvider, { initialServers: initialServers, children: _jsx(McpServer, { uniqueId: 'server-1', showPrompts: true }) }));
        await waitFor(() => {
            expect(fetchToolsMock).toHaveBeenCalled();
        });
        await act(async () => {
            await Promise.resolve();
        });
        await waitFor(() => {
            expect(listPromptsMock).toHaveBeenCalledTimes(1);
        });
        const initialFetchCount = listPromptsMock.mock.calls.length;
        await waitFor(() => {
            expect(latestDashboardProps?.prompts?.[0]?.name).toBe('fresh-prompt-1');
            expect(latestDashboardProps?.serverEnabled).toBe(true);
        });
        await act(async () => {
            latestDashboardProps?.onToggleServer?.(false);
            await Promise.resolve();
        });
        await waitFor(() => {
            expect(latestDashboardProps?.serverEnabled).toBe(false);
            expect(latestDashboardProps?.prompts).toEqual([]);
        });
        expect(listPromptsMock).toHaveBeenCalledTimes(initialFetchCount);
        await act(async () => {
            latestDashboardProps?.onToggleServer?.(true);
            await Promise.resolve();
        });
        await waitFor(() => {
            expect(listPromptsMock.mock.calls.length).toBeGreaterThan(initialFetchCount);
            expect(latestDashboardProps?.serverEnabled).toBe(true);
            expect(latestDashboardProps?.prompts?.[0]?.name).toBe('fresh-prompt-2');
        });
    });
});
