import { adminApi } from './client'
import { unwrapItem } from './helpers'
import { normalizePaginated, normalizeUser } from './normalizers'
import type {
  AdminUserRecord,
  ApiItemResponse,
  ApiListResponse,
  PaginatedResult,
} from './types'

export type UsersQuery = {
  page?: number
  perPage?: number
  search?: string
  role?: string
}

export type UserUpsertPayload = {
  name: string
  email: string
  role: string
  password?: string
  password_confirmation?: string
}

export async function fetchUsers(
  query: UsersQuery
): Promise<PaginatedResult<AdminUserRecord>> {
  const response = await adminApi.get<ApiListResponse<Record<string, unknown>>>(
    '/users',
    {
      params: {
        page: query.page,
        per_page: query.perPage,
        search: query.search || undefined,
        role: query.role || undefined,
      },
    }
  )

  return normalizePaginated(response.data, normalizeUser)
}

export async function createUser(payload: UserUpsertPayload) {
  const response = await adminApi.post<
    ApiItemResponse<Record<string, unknown>>
  >('/users', payload)
  return normalizeUser(unwrapItem(response))
}

export async function updateUser(
  userId: number | string,
  payload: UserUpsertPayload
) {
  const response = await adminApi.put<ApiItemResponse<Record<string, unknown>>>(
    `/users/${userId}`,
    payload
  )
  return normalizeUser(unwrapItem(response))
}

export async function deleteUser(userId: number | string) {
  await adminApi.delete(`/users/${userId}`)
}
