import request from "@/utils/request";

export interface Menu {
  id: number;
  name: string;
  path?: string;
  icon?: string;
  component?: string;
  parentId?: number;
  permission?: string;
  sort: number;
  validState?: number;
  createBy?: number;
  updateBy?: number;
  createTime?: string;
  updateTime?: string;
  children?: Menu[];
  parent?: Menu;
}

export interface CreateMenuForm {
  name: string;
  path?: string;
  icon?: string;
  component?: string;
  parentId?: number;
  permission?: string;
  sort?: number;
}

export interface UpdateMenuForm {
  name?: string;
  path?: string;
  icon?: string;
  component?: string;
  parentId?: number;
  permission?: string;
  sort?: number;
}

// 获取菜单列表（树形结构）
export async function getMenusList(): Promise<Menu[]> {
  const response = await request.get<any, Menu[]>("/api/menus");
  return response;
}

// 获取单个菜单详情
export async function getMenuDetail(id: number): Promise<Menu> {
  const response = await request.get<any, Menu>(`/api/menus/${id}`);
  return response;
}

// 创建菜单
export async function createMenu(data: CreateMenuForm): Promise<Menu> {
  const response = await request.post<any, Menu>("/api/menus", data);
  return response;
}

// 更新菜单
export async function updateMenu(
  id: number,
  data: UpdateMenuForm
): Promise<Menu> {
  const response = await request.put<any, Menu>(`/api/menus/${id}`, data);
  return response;
}

// 删除菜单
export async function deleteMenu(id: number): Promise<void> {
  return await request.delete<any, void>(`/api/menus/${id}`);
}

// 获取当前用户的菜单（根据权限过滤）
export async function getUserMenus(): Promise<Menu[]> {
  const response = await request.get<any, Menu[]>("/api/menus/user-menus");
  return response;
}

// 兼容性导出：保留 menusApi 对象
export const menusApi = {
  getList: getMenusList,
  getDetail: getMenuDetail,
  create: createMenu,
  update: updateMenu,
  delete: deleteMenu,
  getUserMenus: getUserMenus,
};
