'use client'
import { IBaseResponse, IPaginatedData, CustomUseQueryOptions, TPaginationModel, TSearch } from '@/@core/types/api'
import { useCustomQuery } from '@/hooks/api'
import { ICategory } from '@/types/data/categories/category.interface'
import { request } from '@/utils'

export const CATEGORIES_LIST_QUERY_KEY = 'categories-list'

type CategoriesListBaseQuery = (TSearch & Partial<TPaginationModel>) & {
  is_active?: number
  parent_id?: string | null
  with_paginate?: 'yes' | 'no' | string
}

type CategoriesListNonPaginatedQuery = Omit<CategoriesListBaseQuery, 'per_page'> & {
  per_page?: undefined
}

type CategoriesListPaginatedQuery = CategoriesListBaseQuery & {
  per_page: TPaginationModel['per_page']
}

export const useGetCategoriesList: {
  // No per_page → returns IBaseResponse<ICategory[]>
  (
    query?: CategoriesListNonPaginatedQuery,
    options?: CustomUseQueryOptions<IBaseResponse<ICategory[]>>
  ): ReturnType<typeof useCustomQuery<IBaseResponse<ICategory[]>>>

  // per_page exists → returns IBaseResponse<IPaginatedData<ICategory[]>>
  (
    query: CategoriesListPaginatedQuery,
    options?: CustomUseQueryOptions<IBaseResponse<IPaginatedData<ICategory[]>>>
  ): ReturnType<typeof useCustomQuery<IBaseResponse<IPaginatedData<ICategory[]>>>>
} = (
  query?: CategoriesListNonPaginatedQuery | CategoriesListPaginatedQuery,
  options?: CustomUseQueryOptions<IBaseResponse<any>>
) => {
  const queryKey = [CATEGORIES_LIST_QUERY_KEY, query]

  const categoriesList = useCustomQuery<IBaseResponse<any>>(
    queryKey,
    () => {
      const params: Record<string, string> = {}

      if (query) {
        Object.entries(query).forEach(([key, value]) => {
          if (value === undefined || value === '') {
            return
          }

          params[key] = value === null ? 'null' : String(value)
        })
      }

      return request({ url: '/categories', params })
    },
    options
  )

  return categoriesList
}
