import { adminApi } from './client'
import { unwrapItem } from './helpers'
import {
  normalizePermissionGroups,
  normalizeRole,
  normalizeRolesCollection,
} from './normalizers'
import type { ApiItemResponse, PermissionGroup } from './types'

export type RoleUpsertPayload = {
  name: string
  permissions: string[]
}

export async function fetchRoles() {
  const response = await adminApi.get<unknown>('/roles')
  return normalizeRolesCollection(response.data)
}

export async function fetchPermissionsCatalog(): Promise<PermissionGroup[]> {
  const response = await adminApi.get<ApiItemResponse<unknown> | unknown>(
    '/permissions'
  )
  const normalized = normalizePermissionGroups(response.data)

  // eslint-disable-next-line no-console
  console.log('admin.permissions.raw', response.data)
  // eslint-disable-next-line no-console
  console.log('admin.permissions.normalized', normalized)

  return normalized
}

export async function createRole(payload: RoleUpsertPayload) {
  const response = await adminApi.post<
    ApiItemResponse<Record<string, unknown>>
  >('/roles', payload)
  return normalizeRole(unwrapItem(response))
}

export async function updateRole(
  roleId: number | string,
  payload: RoleUpsertPayload
) {
  const response = await adminApi.put<ApiItemResponse<Record<string, unknown>>>(
    `/roles/${roleId}`,
    payload
  )
  return normalizeRole(unwrapItem(response))
}

export async function deleteRole(roleId: number | string) {
  await adminApi.delete(`/roles/${roleId}`)
}
