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

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

function mapDeptToFrontend(d: any) {
  if (!d) return d;
  return {
    ...d,
    name: d.dept_name || d.name,
    leader: d.leader || "",
    phone: d.phone || "",
    email: d.email || "",
    sort: d.order_num || d.sort || 0,
    status: d.status === "0" ? "enabled" : "disabled",
    parentId: d.parent_id,
    createTime: d.create_time,
    updateTime: d.update_time,
  };
}

function mapDeptToBackend(data: Record<string, unknown>) {
  const result: Record<string, unknown> = { ...data };
  if (result.name !== undefined) { result.dept_name = result.name; delete result.name; }
  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 === "enabled") { result.status = "0"; }
  if (result.status === "disabled") { result.status = "1"; }
  return result;
}

/**
 * 部门树
 */
export async function getDeptTree(params?: Record<string, unknown>): Promise<ApiResponse<any[]>> {
  const res: any = await request.get("/sys/dept/list", { params });
  if (res.code === 1 && res.data) {
    res.data = (res.data || []).map(mapDeptToFrontend);
  }
  return res;
}

/**
 * 部门列表
 */
export const getDeptList = getDeptTree;

/**
 * 部门详情
 */
export async function getDeptById(id: string): Promise<ApiResponse<any>> {
  const res: any = await request.get("/sys/dept/detail", { params: { id } });
  if (res.code === 1 && res.data) {
    res.data = mapDeptToFrontend(res.data);
  }
  return res;
}

/**
 * 新增/编辑部门
 */
export function saveDept(data: Record<string, unknown>): Promise<ApiResponse<any>> {
  return request.post("/sys/dept/save", mapDeptToBackend(data));
}

export const createDept = saveDept;
export const updateDept = saveDept;

/**
 * 删除部门
 */
export function deleteDept(id: string): Promise<ApiResponse<any>> {
  return request.post("/sys/dept/delete", { id });
}
