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

export interface Role {
  id: number
  name: string
  code: string
  description: string | null
  status: number
  sortOrder: number
  createdAt: string
}

export interface RoleQuery {
  keyword?: string
  status?: number
  page: number
  pageSize: number
}

export interface CreateRoleRequest {
  name: string
  code: string
  description?: string
  status: number
  sortOrder: number
}

export interface UpdateRoleRequest extends CreateRoleRequest {
  id: number
}

export interface AssignMenusRequest {
  roleId: number
  menuIds: number[]
}

export interface AssignPermissionsRequest {
  roleId: number
  permissionCodes: string[]
}

// 获取角色列表
export function getRoleList(params: RoleQuery): Promise<ApiResponse<PagedResult<Role>>> {
  return request({
    url: '/admin/roles',
    method: 'get',
    params
  })
}

// 获取所有角色（不分页）
export function getAllRoles(): Promise<ApiResponse<Role[]>> {
  return request({
    url: '/admin/roles/all',
    method: 'get'
  })
}

// 获取角色详情
export function getRole(id: number): Promise<ApiResponse<Role>> {
  return request({
    url: `/admin/roles/${id}`,
    method: 'get'
  })
}

// 创建角色
export function createRole(data: CreateRoleRequest): Promise<ApiResponse<Role>> {
  return request({
    url: '/admin/roles',
    method: 'post',
    data
  })
}

// 更新角色
export function updateRole(id: number, data: UpdateRoleRequest): Promise<ApiResponse<null>> {
  return request({
    url: `/admin/roles/${id}`,
    method: 'put',
    data
  })
}

// 删除角色
export function deleteRole(id: number): Promise<ApiResponse<null>> {
  return request({
    url: `/admin/roles/${id}`,
    method: 'delete'
  })
}

// 获取角色菜单
export function getRoleMenus(roleId: number): Promise<ApiResponse<number[]>> {
  return request({
    url: `/admin/roles/${roleId}/menus`,
    method: 'get'
  })
}

// 分配角色菜单
export function assignRoleMenus(data: AssignMenusRequest): Promise<ApiResponse<null>> {
  return request({
    url: `/admin/roles/${data.roleId}/menus`,
    method: 'put',
    data: { menuIds: data.menuIds }
  })
}

// 获取角色权限
export function getRolePermissions(roleId: number): Promise<ApiResponse<string[]>> {
  return request({
    url: `/admin/roles/${roleId}/permissions`,
    method: 'get'
  })
}

// 分配角色权限
export function assignRolePermissions(data: AssignPermissionsRequest): Promise<ApiResponse<null>> {
  return request({
    url: `/admin/roles/${data.roleId}/permissions`,
    method: 'put',
    data: { permissionCodes: data.permissionCodes }
  })
}
