export const permissionCodes = {
  webgisView: "webgis.view",
  webgisEdit: "webgis.edit",
  scadaView: "scada.view",
  scadaClean: "scada.clean",
  simulationView: "simulation.view",
  simulationRun: "simulation.run",
  burstView: "burst.view",
  burstRun: "burst.run",
  riskView: "risk.view",
  riskRun: "risk.run",
  optimizationView: "optimization.view",
  optimizationRun: "optimization.run",
  modelImport: "model.import",
  auditView: "audit.view",
  environmentManage: "environment.manage",
  membershipManage: "membership.manage",
} as const;

export type PermissionCode =
  (typeof permissionCodes)[keyof typeof permissionCodes];

export type AccessContext = {
  user_id: string;
  username: string;
  system_role: string;
  is_system_admin: boolean;
  project_id?: string | null;
  project_role?: string | null;
  permissions: string[];
};

export const resourcePermissions: Record<string, PermissionCode> = {
  "管网在线模拟": permissionCodes.simulationView,
  "SCADA 数据清洗": permissionCodes.scadaClean,
  "监测点优化布置": permissionCodes.optimizationRun,
  "健康风险分析": permissionCodes.riskRun,
  "爆管模拟": permissionCodes.burstRun,
  "爆管侦测": permissionCodes.burstRun,
  "爆管定位": permissionCodes.burstRun,
  "DMA 漏损识别": permissionCodes.burstRun,
  "水质模拟": permissionCodes.simulationRun,
  "管道冲洗": permissionCodes.simulationRun,
  "系统管理": permissionCodes.environmentManage,
  "审计日志": permissionCodes.auditView,
};

export const pathPermissions: Array<{
  prefix: string;
  permission: PermissionCode;
}> = [
  { prefix: "/system-admin", permission: permissionCodes.environmentManage },
  { prefix: "/audit-logs", permission: permissionCodes.auditView },
  { prefix: "/scada-data-cleaning", permission: permissionCodes.scadaClean },
  {
    prefix: "/monitoring-place-optimization",
    permission: permissionCodes.optimizationRun,
  },
  { prefix: "/health-risk-analysis", permission: permissionCodes.riskRun },
  {
    prefix: "/hydraulic-simulation/burst-simulation",
    permission: permissionCodes.burstRun,
  },
  {
    prefix: "/hydraulic-simulation/burst-detection",
    permission: permissionCodes.burstRun,
  },
  {
    prefix: "/hydraulic-simulation/burst-location",
    permission: permissionCodes.burstRun,
  },
  {
    prefix: "/hydraulic-simulation/dma-leak-detection",
    permission: permissionCodes.burstRun,
  },
  {
    prefix: "/hydraulic-simulation/contaminant-simulation",
    permission: permissionCodes.simulationRun,
  },
  {
    prefix: "/hydraulic-simulation/flushing-analysis",
    permission: permissionCodes.simulationRun,
  },
  {
    prefix: "/network-simulation",
    permission: permissionCodes.simulationView,
  },
];

export const permissionForPath = (pathname: string) =>
  pathPermissions.find(({ prefix }) => pathname.startsWith(prefix))?.permission;
