import { get, post, put, del } from '@/lib/http/client'
import type { PaginatedData } from '@/types/http'
import type {
  Role,
  RoleListParams,
  CreateRoleRequest,
  UpdateRoleRequest,
} from '@/types/role'
import type { Permission } from '@/types/permission'

export function listRoles(params?: RoleListParams): Promise<PaginatedData<Role>> {
  return get<PaginatedData<Role>>(
    '/roles',
    params as Record<string, string | number | boolean | undefined>,
  )
}

export function getRole(id: number): Promise<Role> {
  return get<Role>(`/roles/${id}`)
}

export function createRole(data: CreateRoleRequest): Promise<Role> {
  return post<Role>('/roles', data)
}

export function updateRole(id: number, data: UpdateRoleRequest): Promise<Role> {
  return put<Role>(`/roles/${id}`, data)
}

export function deleteRole(id: number): Promise<void> {
  return del<void>(`/roles/${id}`)
}

export function updateRoleStatus(id: number, status: 0 | 1): Promise<void> {
  return put<void>(`/roles/${id}/status`, { status })
}

export async function getRolePermissions(id: number): Promise<number[]> {
  const permissions = await get<Permission[]>(`/roles/${id}/permissions`)
  return permissions.map((permission) => permission.id)
}

export function assignRolePermissions(id: number, permissionIds: number[]): Promise<void> {
  return put<void>(`/roles/${id}/permissions`, { permission_ids: permissionIds })
}
