export interface SidebarMenuInput {
  code: string;
  name: string;
  path: string;
}

export interface SidebarMenuSection {
  code: string;
  title: string;
  items: SidebarMenuInput[];
}

const DASHBOARD_MENU: SidebarMenuInput = {
  code: "dashboard",
  name: "工作台",
  path: "/dashboard",
};

const MENU_LABELS: Record<string, string> = {
  monthly_payroll: "工资核算",
  commissions: "提成录入",
  salary_profiles: "薪资档案",
  reports: "工资报表",
};

const SECTION_DEFINITIONS: Array<{
  code: string;
  title: string;
  itemCodes: string[];
}> = [
  {
    code: "core",
    title: "核心工作",
    itemCodes: ["dashboard", "attendance_realtime"],
  },
  {
    code: "monthly",
    title: "月度核算",
    itemCodes: ["monthly_payroll", "commissions"],
  },
  {
    code: "employee",
    title: "员工薪资",
    itemCodes: ["employees", "salary_profiles", "organization"],
  },
  {
    code: "reports",
    title: "报表分析",
    itemCodes: ["reports"],
  },
  {
    code: "system",
    title: "系统管理",
    itemCodes: ["configs", "users", "operation_logs"],
  },
];

export function buildSidebarSections(backendMenus: SidebarMenuInput[]): SidebarMenuSection[] {
  const menuByCode = new Map<string, SidebarMenuInput>();
  menuByCode.set(DASHBOARD_MENU.code, DASHBOARD_MENU);
  for (const menu of backendMenus) {
    menuByCode.set(menu.code, menu);
  }

  return SECTION_DEFINITIONS.map((section) => ({
    code: section.code,
    title: section.title,
    items: section.itemCodes
      .map((code) => menuByCode.get(code))
      .filter((item): item is SidebarMenuInput => Boolean(item))
      .map(normalizeMenuLabel),
  })).filter((section) => section.items.length > 0);
}

function normalizeMenuLabel(menu: SidebarMenuInput): SidebarMenuInput {
  return {
    ...menu,
    name: MENU_LABELS[menu.code] || menu.name,
  };
}
