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

export type MenusQuery = {
  page?: number
  perPage?: number
  location?: string
}

export type MenuUpsertPayload = {
  label: string
  url: string
  location: string
  type?: string
  parent_id?: number | null
  order_index?: number
  is_active?: boolean
}

export type MenuReorderItem = {
  id: number | string
  parent_id: number | null
  order_index: number
}

export async function fetchMenus(
  query: MenusQuery
): Promise<PaginatedResult<AdminMenuRecord>> {
  const response = await adminApi.get<ApiListResponse<Record<string, unknown>>>(
    '/menus',
    {
      params: {
        page: query.page,
        per_page: query.perPage,
        location: query.location || undefined,
      },
    }
  )

  return normalizePaginated(response.data, normalizeMenu)
}

export async function fetchMenu(menuId: number | string) {
  const response = await adminApi.get<ApiItemResponse<Record<string, unknown>>>(
    `/menus/${menuId}`
  )
  return normalizeMenu(unwrapItem(response))
}

export async function createMenu(payload: MenuUpsertPayload) {
  const response = await adminApi.post<
    ApiItemResponse<Record<string, unknown>>
  >('/menus', payload)
  return normalizeMenu(unwrapItem(response))
}

export async function updateMenu(
  menuId: number | string,
  payload: MenuUpsertPayload
) {
  const response = await adminApi.put<ApiItemResponse<Record<string, unknown>>>(
    `/menus/${menuId}`,
    payload
  )
  return normalizeMenu(unwrapItem(response))
}

export async function deleteMenu(menuId: number | string) {
  await adminApi.delete(`/menus/${menuId}`)
}

export async function reorderMenus(items: MenuReorderItem[]) {
  await adminApi.post('/menus/reorder', { items })
}
