'use client'

import { useCustomQuery } from '@/hooks/api'
import { request } from '@/utils'
import type { CustomUseQueryOptions } from '@/@core/types/api'
import type { ICategory } from '@/types/data/categories/category.interface'

export const CATEGORIES_DROPDOWN_QUERY_KEY = 'categories-dropdown-list'

export type CategoriesDropdownQuery = {
  search?: string
  sort_by?: string
  sort_as?: 'asc' | 'desc'
}

const normalizeCategories = (categories?: ICategory[]): ICategory[] => {
  if (!Array.isArray(categories)) {
    return []
  }

  return categories.map(category => {
    const nestedSource = Array.isArray(category.children)
      ? category.children
      : Array.isArray(category.subcategories)
        ? category.subcategories
        : undefined

    return {
      ...category,
      children: normalizeCategories(nestedSource)
    }
  })
}

const mapDropdownResponse = (res: any): ICategory[] => {
  if (Array.isArray(res)) {
    return normalizeCategories(res)
  }

  if (Array.isArray(res?.data)) {
    return normalizeCategories(res.data as ICategory[])
  }

  if (Array.isArray(res?.data?.data)) {
    return normalizeCategories(res.data.data as ICategory[])
  }

  return []
}

export const useGetCategoriesDropdown = (
  query?: CategoriesDropdownQuery,
  options?: CustomUseQueryOptions<ICategory[]>
) => {
  const queryKey = [CATEGORIES_DROPDOWN_QUERY_KEY, query]

  return useCustomQuery<ICategory[]>(
    queryKey,
    async () => {
      const params: Record<string, string> = {}

      if (query) {
        Object.entries(query).forEach(([key, value]) => {
          if (value !== undefined && value !== null && value !== '') {
            params[key] = String(value)
          }
        })
      }

      const response = await request({ url: '/categories/dropdown/list', params })

      return mapDropdownResponse(response)
    },
    options
  )
}
