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

export const PRODUCTS_LIST_QUERY_KEY = 'simple-products-list'

export const useGetProductsList: {
  (
    query: (TPaginationModel & TSearch) & { with_paginate: 'no'; with_relations?: 1; with_relations_count?: 1 },
    options?: CustomUseQueryOptions<IBaseResponse<IProduct[]>>
  ): ReturnType<typeof useCustomQuery<IBaseResponse<IProduct[]>>>

  (
    query?: (TPaginationModel & TSearch & { is_available?: string | boolean }) & {
      with_relations?: 1
      with_relations_count?: 1
    },
    options?: CustomUseQueryOptions<IBaseResponse<IPaginatedData<IProduct[]>>>
  ): ReturnType<typeof useCustomQuery<IBaseResponse<IPaginatedData<IProduct[]>>>>
} = (query?: TPaginationModel & TSearch, options?: CustomUseQueryOptions<IBaseResponse<any>>) => {
  const queryKey = [PRODUCTS_LIST_QUERY_KEY, query]

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

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

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

  return productsList
}
