import client from './client';

export interface MenuInfo {
  id: string;
  parent_id?: string;
  title: string;
  path?: string;
  icon?: string;
  sort_order: number;
  visible: boolean;
  menu_type: string;
  permission?: string;
  children?: MenuInfo[];
  version: number;
}

export interface MenuItemReq {
  id?: string;
  parent_id?: string;
  title: string;
  path?: string;
  icon?: string;
  sort_order?: number;
  visible?: boolean;
  menu_type?: string;
  permission?: string;
  role_ids?: string[];
  version?: number;
}

export async function getMenus() {
  const { data } = await client.get<{ success: boolean; data: MenuInfo[] }>('/config/menus');
  return data.data;
}

export async function getMenusForUser() {
  const { data } = await client.get<{ success: boolean; data: MenuInfo[] }>('/menus/user');
  return data.data;
}

export async function batchSaveMenus(menus: MenuItemReq[]) {
  await client.put('/config/menus', { menus });
}

export async function createMenu(req: MenuItemReq) {
  const { data } = await client.post<{ success: boolean; data: MenuInfo }>(
    '/config/menus',
    req,
  );
  return data.data;
}

export async function updateMenu(id: string, req: MenuItemReq) {
  const { data } = await client.put<{ success: boolean; data: MenuInfo }>(
    `/config/menus/${id}`,
    req,
  );
  return data.data;
}

export async function deleteMenu(id: string, version: number) {
  await client.delete(`/config/menus/${id}`, { data: { version } });
}
