import { request, type ApiResponse } from '@/utils/request'

export interface Department {
  id: number
  parentId: number
  name: string
  code: string
  sortOrder: number
  status: number
  createdAt: string
}

export interface DepartmentTree extends Department {
  children: DepartmentTree[]
}

export interface CreateDepartmentRequest {
  parentId: number
  name: string
  code: string
  sortOrder: number
  status: number
}

export interface UpdateDepartmentRequest extends CreateDepartmentRequest {
  id: number
}

export interface AssignDepartmentMenusRequest {
  departmentId: number
  menuIds: number[]
}

// 获取部门树
export function getDepartmentTree(): Promise<ApiResponse<DepartmentTree[]>> {
  return request({
    url: '/admin/departments',
    method: 'get'
  })
}

// 获取部门详情
export function getDepartment(id: number): Promise<ApiResponse<Department>> {
  return request({
    url: `/admin/departments/${id}`,
    method: 'get'
  })
}

// 创建部门
export function createDepartment(data: CreateDepartmentRequest): Promise<ApiResponse<Department>> {
  return request({
    url: '/admin/departments',
    method: 'post',
    data
  })
}

// 更新部门
export function updateDepartment(id: number, data: UpdateDepartmentRequest): Promise<ApiResponse<null>> {
  return request({
    url: `/admin/departments/${id}`,
    method: 'put',
    data
  })
}

// 删除部门
export function deleteDepartment(id: number): Promise<ApiResponse<null>> {
  return request({
    url: `/admin/departments/${id}`,
    method: 'delete'
  })
}

// 获取部门菜单
export function getDepartmentMenus(departmentId: number): Promise<ApiResponse<number[]>> {
  return request({
    url: `/admin/departments/${departmentId}/menus`,
    method: 'get'
  })
}

// 分配部门菜单
export function assignDepartmentMenus(data: AssignDepartmentMenusRequest): Promise<ApiResponse<null>> {
  return request({
    url: `/admin/departments/${data.departmentId}/menus`,
    method: 'put',
    data: { menuIds: data.menuIds }
  })
}
