namespace MiGu.Server.Auth;

/// <summary>
/// 单个「权限页面」定义。Key 与前端 vue-router 的 route.name 一一对齐，
/// 角色通过勾选 Key 集合决定可访问的页面（菜单 + 路由守卫据此放行）。
/// </summary>
public sealed record PageDef(string Key, string Label, string Group, string Scope);

/// <summary>
/// 平台「权限页面清单」——RBAC 的最小授权单元。
///
/// 设计：页面是由前端路由静态决定的（相对稳定），因此后端维护一份与
/// <c>frontends/.../router/index.ts</c> 对齐的静态清单，通过 <c>GET /api/rbac/pages</c>
/// 暴露给「权限与角色」管理页，让管理员可视化地把页面分配给角色。
///
/// Scope 含义：
/// - <c>Platform</c>：管理端（/admin/*）页面；
/// - <c>RCSMonitor</c>：运营监控端（/monitor/*）页面。
/// </summary>
public static class PageCatalog
{
    public const string ScopePlatform = "Platform";
    public const string ScopeMonitor = "RCSMonitor";

    /// <summary>权限页面通配符：角色 Pages 含此值表示「该 scope 下全部页面」（超级管理员）。</summary>
    public const string Wildcard = "*";

    public static readonly IReadOnlyList<PageDef> All = new List<PageDef>
    {
        // ── 管理端 / Platform：概览 ──
        new("admin-dashboard", "总览", "概览", ScopePlatform),
        new("admin-map-monitor", "地图监控", "概览", ScopePlatform),
        new("admin-tasks", "任务管理", "概览", ScopePlatform),
        new("admin-alarms", "报警管理", "概览", ScopePlatform),

        // ── 管理端 / Platform：设计与编排 ──
        new("admin-maps", "地图管理", "设计与编排", ScopePlatform),
        new("admin-map-editor", "地图编辑", "设计与编排", ScopePlatform),
        new("admin-project-properties", "项目属性", "设计与编排", ScopePlatform),
        new("admin-tracks", "场景管理", "设计与编排", ScopePlatform),
        new("admin-cars", "车辆管理", "设计与编排", ScopePlatform),
        new("admin-processes", "进程管理", "设计与编排", ScopePlatform),
        new("admin-scripts", "脚本管理", "设计与编排", ScopePlatform),
        new("admin-task-templates", "任务编排", "设计与编排", ScopePlatform),
        new("admin-simple-fields", "字段管理", "设计与编排", ScopePlatform),

        // ── 管理端 / Platform：平台配置中心（聚合页，每个 Key 对齐前端聚合路由 route.name） ──
        new("admin-config-strategy", "调度策略", "平台配置中心", ScopePlatform),
        new("admin-vehicle-hub", "车辆运维", "平台配置中心", ScopePlatform),
        new("admin-config-facility", "设备接入", "平台配置中心", ScopePlatform),
        new("admin-config-warehouse", "库位管理", "平台配置中心", ScopePlatform),
        new("admin-config-business", "业务与集成", "平台配置中心", ScopePlatform),
        new("admin-config-ops-center", "运维与回放", "平台配置中心", ScopePlatform),
        new("admin-config-system-center", "系统与权限", "平台配置中心", ScopePlatform),

        // ── 运营端 / RCSMonitor ──
        new("monitor-dashboard", "运营总览", "运营监控", ScopeMonitor),
        new("monitor-vehicle-hub", "车辆运维", "运营监控", ScopeMonitor),
        new("monitor-map", "地图监控", "运营监控", ScopeMonitor),
        new("monitor-ops", "运维操作", "运营监控", ScopeMonitor),
        new("monitor-notes", "运营备注", "运营监控", ScopeMonitor),
    };

    private static readonly HashSet<string> _keys =
        All.Select(p => p.Key).ToHashSet(StringComparer.OrdinalIgnoreCase);

    /// <summary>已下线页面 Key → 合并后的新 Key（角色数据迁移用）。</summary>
    private static readonly IReadOnlyDictionary<string, string> LegacyKeyAliases =
        new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
        {
            ["admin-config-vehicle"] = "admin-vehicle-hub",
            ["admin-config-fleet"] = "admin-vehicle-hub",
            // 会话 16：平台配置中心入口按业务收敛为 6 个聚合页，旧 Key 迁移到对应聚合页 Key。
            ["admin-config-routing"] = "admin-config-strategy",
            ["admin-config-task"] = "admin-config-strategy",
            ["admin-config-traffic"] = "admin-config-strategy",
            ["admin-config-charge"] = "admin-config-strategy",
            ["admin-config-device"] = "admin-config-facility",
            ["admin-config-location"] = "admin-config-warehouse",
            ["admin-config-integrations"] = "admin-config-business",
            ["admin-config-scenario"] = "admin-config-business",
            ["admin-config-widget"] = "admin-config-business",
            ["admin-playback"] = "admin-config-ops-center",
            ["admin-config-ops"] = "admin-config-ops-center",
            ["admin-config-logs"] = "admin-config-ops-center",
            ["admin-config-map-monitor"] = "admin-config-ops-center",
            ["admin-config-system"] = "admin-config-system-center",
            ["admin-config-auth"] = "admin-config-system-center",
        };

    /// <summary>判断页面 Key 是否合法（用于角色保存时过滤掉脏数据 / 已下线页面）。</summary>
    public static bool IsValidKey(string key) => _keys.Contains(key);

    /// <summary>将旧页面 Key 映射为当前有效 Key；未知 Key 原样返回。</summary>
    public static string NormalizeKey(string key) =>
        LegacyKeyAliases.TryGetValue(key, out var mapped) ? mapped : key;

    /// <summary>列出某 scope 下的全部页面 Key（用于把角色的 "*" 通配展开成具体页面集合）。</summary>
    public static IReadOnlyList<string> KeysForScope(string scope) =>
        All.Where(p => string.Equals(p.Scope, scope, StringComparison.OrdinalIgnoreCase))
           .Select(p => p.Key)
           .ToList();
}
