import type { ApiResponse } from "@/types/api";
import type { Permission } from "@/types/auth";

import { request } from "@/utils/request";

function mapPermToFrontend(p: any) {
  if (!p) return p;
  return {
    ...p,
    name: p.menu_name || p.name,
    code: p.perms || p.code,
    type: p.menu_type === "M" ? "menu" : p.menu_type === "C" ? "menu" : "button",
    path: p.path || "",
    component: p.component || "",
    icon: p.icon || "",
    sort: p.order_num || p.sort || 0,
    status: p.status === "0" ? "active" : "inactive",
    visible: p.visible !== "1",
    parentId: p.parent_id,
    createTime: p.create_time,
    updateTime: p.update_time,
    children: p.children ? p.children.map(mapPermToFrontend) : undefined,
  };
}

function mapPermToBackend(data: Record<string, unknown>) {
  const result: Record<string, unknown> = { ...data };
  if (result.name !== undefined) { result.menu_name = result.name; delete result.name; }
  if (result.code !== undefined) { result.perms = result.code; delete result.code; }
  if (result.parentId !== undefined) { result.parent_id = result.parentId; delete result.parentId; }
  if (result.sort !== undefined) { result.order_num = result.sort; delete result.sort; }
  if (result.status === "active") { result.status = "0"; }
  if (result.status === "inactive") { result.status = "1"; }
  return result;
}

/**
 * 获取权限列表 (tree)
 */
export async function getPermissionList(
  params?: Record<string, unknown>,
): Promise<ApiResponse<Permission[]>> {
  const res: any = await request.get("/sys/menu/tree", { params });
  if (res.code === 1 && res.data) {
    res.data = (res.data || []).map(mapPermToFrontend);
  }
  return res;
}

/**
 * 获取权限树
 */
export const getPermissionTree = getPermissionList;

/**
 * 根据ID获取权限
 */
export async function getPermissionById(
  id: string,
): Promise<ApiResponse<Permission>> {
  const res: any = await request.get("/sys/menu/detail", { params: { id } });
  if (res.code === 1 && res.data) {
    res.data = mapPermToFrontend(res.data);
  }
  return res;
}

/**
 * 创建权限
 */
export async function createPermission(
  data: Partial<Permission>,
): Promise<ApiResponse<Permission>> {
  return request.post("/sys/menu/save", mapPermToBackend(data as Record<string, unknown>));
}

/**
 * 更新权限
 */
export async function updatePermission(
  id: string,
  data: Partial<Permission>,
): Promise<ApiResponse<Permission>> {
  return request.post("/sys/menu/save", mapPermToBackend({ ...data, id }));
}

/**
 * 删除权限
 */
export async function deletePermission(id: string): Promise<ApiResponse<null>> {
  return request.post("/sys/menu/delete", { id });
}

/**
 * 获取当前用户权限
 */
export async function getUserPermissions(): Promise<ApiResponse<Permission[]>> {
  return request.get("/auth/user_permissions");
}
