import { describe, expect, test } from "vitest";
import {
    findSecondLevelNavItemByPath,
    getFrequentSecondLevelMenus,
    recordSecondLevelMenuVisit,
} from "@/app/navigation/menuUsage.js";

const user = { account: "admin", id: 1 };
const appCode = "lalu";
const menus = [
    { code: "overview", id: "overview", label: "系统概览", path: "/overview" },
    {
        code: "app-users",
        id: "app-users",
        label: "用户管理",
        children: [
            { code: "app-user-list", id: "app-user-list", label: "用户列表", path: "/app/users" },
            { code: "app-user-login-logs", id: "app-user-login-logs", label: "登录日志", path: "/app/users/login-logs" },
        ],
    },
    {
        code: "resources",
        id: "resources",
        label: "资源管理",
        children: [{ code: "gift-list", id: "gift-list", label: "礼物列表", path: "/resources/gifts" }],
    },
];

describe("menu usage cache", () => {
    test("matches the best second-level menu for nested paths", () => {
        expect(findSecondLevelNavItemByPath("/app/users/login-logs/123", menus)).toMatchObject({
            code: "app-user-login-logs",
            parentLabel: "用户管理",
        });
        expect(findSecondLevelNavItemByPath("/overview", menus)).toBeUndefined();
    });

    test("records second-level visits and returns frequent cards", () => {
        const storage = memoryStorage();
        recordSecondLevelMenuVisit({ appCode, menus, now: 1000, pathname: "/app/users", storage, user });
        recordSecondLevelMenuVisit({ appCode, menus, now: 2500, pathname: "/resources/gifts", storage, user });
        recordSecondLevelMenuVisit({ appCode, menus, now: 4000, pathname: "/app/users", storage, user });
        recordSecondLevelMenuVisit({ appCode, menus, now: 4100, pathname: "/app/users", storage, user });
        recordSecondLevelMenuVisit({ appCode, menus, now: 6000, pathname: "/overview", storage, user });

        const items = getFrequentSecondLevelMenus({ appCode, menus, storage, user });
        expect(items.map((item) => [item.code, item.count])).toEqual([
            ["app-user-list", 2],
            ["gift-list", 1],
        ]);
    });

    test("drops cached menus that are no longer visible", () => {
        const storage = memoryStorage();
        recordSecondLevelMenuVisit({ appCode, menus, now: 1000, pathname: "/resources/gifts", storage, user });

        const visibleMenus = menus.filter((item) => item.code !== "resources");
        expect(getFrequentSecondLevelMenus({ appCode, menus: visibleMenus, storage, user })).toEqual([]);
    });
});

function memoryStorage() {
    const values = new Map();
    return {
        getItem: (key) => values.get(key) || null,
        removeItem: (key) => values.delete(key),
        setItem: (key, value) => values.set(key, String(value)),
    };
}
