//
//  HomeCommonMenuStoreTests.swift
//  suixinkanTests
//
//  Created by Codex on 2026/6/22.
//

import XCTest
@testable import suixinkan

/// 首页常用应用存储测试，覆盖默认值、过滤和别名去重。
final class HomeCommonMenuStoreTests: XCTestCase {
    /// 测试首次无配置时会生成默认常用应用。
    func testLoadCreatesDefaultCommonMenusWhenBaselineIsMissing() {
        let defaults = makeIsolatedDefaults()
        let store = HomeCommonMenuStore(defaults: defaults)
        let menus = [
            menu("registration_invitation"),
            menu("location_report"),
            menu("pm_manager")
        ]

        let uris = store.load(menuItems: menus)

        XCTAssertEqual(uris, ["registration_invitation", "location_report", "pm_manager"])
        XCTAssertTrue(defaults.bool(forKey: HomeCommonMenuStore.defaultBaselineKey))
    }

    /// 测试已保存 URI 会按当前权限过滤并解析同义 URI。
    func testLoadFiltersSavedUrisByCurrentPermissions() {
        let defaults = makeIsolatedDefaults()
        defaults.set(true, forKey: HomeCommonMenuStore.defaultBaselineKey)
        defaults.set(["task_management", "unknown", "pm"], forKey: HomeCommonMenuStore.defaultStorageKey)
        let store = HomeCommonMenuStore(defaults: defaults)
        let menus = [
            menu("task_management_editor"),
            menu("pm_manager")
        ]

        let uris = store.load(menuItems: menus)

        XCTAssertEqual(uris, ["task_management_editor", "pm_manager"])
    }

    /// 测试添加常用应用时会按同义 URI 去重。
    func testAddDeduplicatesAliases() {
        let defaults = makeIsolatedDefaults()
        let store = HomeCommonMenuStore(defaults: defaults)
        let menus = [
            menu("task_management_editor")
        ]

        let uris = store.add("task_management", current: ["task_management_editor"], menuItems: menus)

        XCTAssertEqual(uris, ["task_management_editor"])
    }

    /// 测试移除常用应用时会移除同义 URI。
    func testRemoveDeletesAliases() {
        let defaults = makeIsolatedDefaults()
        let store = HomeCommonMenuStore(defaults: defaults)

        let uris = store.remove("pm", current: ["pm_manager", "location_report"])

        XCTAssertEqual(uris, ["location_report"])
    }

    /// 创建测试菜单实体。
    private func menu(_ uri: String) -> HomeMenuItem {
        HomeMenuItem(title: HomeMenuRouter.title(for: uri), uri: uri, iconSrc: nil)
    }

    /// 创建独立 UserDefaults，避免测试污染真实 App 偏好。
    private func makeIsolatedDefaults() -> UserDefaults {
        let suiteName = "suixinkan.home.tests.\(UUID().uuidString)"
        let defaults = UserDefaults(suiteName: suiteName)!
        defaults.removePersistentDomain(forName: suiteName)
        return defaults
    }
}
