import request from "@/utils/request";
import type { PaginationParams, PaginationResponse } from "@/types/api";

export interface Department {
  id: number;
  tenantId: number;
  name: string;
  code: string;
  parentId?: number | null;
  description?: string;
  sort: number;
  validState: number;
  createBy?: number;
  updateBy?: number;
  createTime?: string;
  updateTime?: string;
  parent?: Department;
  children?: Department[];
  _count?: {
    teachers: number;
    children: number;
  };
}

export interface CreateDepartmentForm {
  name: string;
  code: string;
  parentId?: number;
  description?: string;
  sort?: number;
}

export interface UpdateDepartmentForm {
  name?: string;
  code?: string;
  parentId?: number | null;
  description?: string;
  sort?: number;
}

// 获取部门列表
export async function getDepartmentsList(
  params: PaginationParams & { parentId?: number }
): Promise<PaginationResponse<Department>> {
  const response = await request.get<any, PaginationResponse<Department>>("/api/departments", {
    params,
  });
  return response;
}

// 获取部门树
export async function getDepartmentsTree(): Promise<Department[]> {
  const response = await request.get<any, Department[]>("/api/departments/tree");
  return response;
}

// 获取单个部门详情
export async function getDepartmentDetail(id: number): Promise<Department> {
  const response = await request.get<any, Department>(`/api/departments/${id}`);
  return response;
}

// 创建部门
export async function createDepartment(data: CreateDepartmentForm): Promise<Department> {
  const response = await request.post<any, Department>("/api/departments", data);
  return response;
}

// 更新部门
export async function updateDepartment(
  id: number,
  data: UpdateDepartmentForm
): Promise<Department> {
  const response = await request.put<any, Department>(`/api/departments/${id}`, data);
  return response;
}

// 删除部门
export async function deleteDepartment(id: number): Promise<void> {
  return await request.delete<any, void>(`/api/departments/${id}`);
}

export const departmentsApi = {
  getList: getDepartmentsList,
  getTree: getDepartmentsTree,
  getDetail: getDepartmentDetail,
  create: createDepartment,
  update: updateDepartment,
  delete: deleteDepartment,
};

