import { fireEvent, render, screen } from "@testing-library/react";
import { expect, test, vi } from "vitest";
import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
import { QueryProvider } from "@/shared/query/QueryProvider.jsx";
import { ConfirmProvider } from "@/shared/ui/ConfirmProvider.jsx";
import { ToastProvider } from "@/shared/ui/ToastProvider.jsx";
import { getAppUser } from "@/features/app-users/api";
import { AppUserDetailPage } from "@/features/app-users/pages/AppUserDetailPage.jsx";

// AppUserDetailView 会静态导入 issueAppUserAccessToken，mock 工厂缺少该导出会直接导致模块加载失败。
vi.mock("@/features/app-users/api", () => ({
    getAppUser: vi.fn(),
    issueAppUserAccessToken: vi.fn(),
    revokeAppUserResource: vi.fn(),
}));

test("full user detail route loads the URL user and returns to its source list", async () => {
    vi.mocked(getAppUser).mockResolvedValue({
        age: 24,
        defaultDisplayUserId: "163337",
        gender: "female",
        levels: {
            charm: { displayLevel: 3, realLevel: 3 },
            game: { displayLevel: 6, realLevel: 6 },
            wealth: { displayLevel: 4, realLevel: 4 },
        },
        status: "active",
        userId: "10001",
        username: "tester",
        vip: { active: false, level: 0 },
    });

    render(
        <QueryProvider>
            <ToastProvider>
                <ConfirmProvider>
                    <MemoryRouter
                        initialEntries={[
                            {
                                pathname: "/app/users/10001",
                                state: { from: "/app/users?status=active" },
                            },
                        ]}
                    >
                        <Routes>
                            <Route path="/app/users/:userId" element={<AppUserDetailPage />} />
                            <Route path="/app/users" element={<LocationValue />} />
                        </Routes>
                    </MemoryRouter>
                </ConfirmProvider>
            </ToastProvider>
        </QueryProvider>,
    );

    expect((await screen.findAllByText("tester")).length).toBeGreaterThan(0);
    expect(getAppUser).toHaveBeenCalledWith("10001");
    expect(screen.getByRole("tab", { name: "总览" })).toBeInTheDocument();
    expect(screen.queryByRole("link", { name: /完整详情/ })).not.toBeInTheDocument();

    fireEvent.click(screen.getByRole("button", { name: /返回用户列表/ }));
    expect(await screen.findByTestId("location-value")).toHaveTextContent("/app/users?status=active");
});

function LocationValue() {
    const location = useLocation();
    return <span data-testid="location-value">{`${location.pathname}${location.search}`}</span>;
}
