'use client'

import { IBaseResponse, IPaginatedData, CustomUseQueryOptions, TPaginationModel, TSearch } from '@/@core/types/api'
import { useCustomQuery } from '@/hooks/api'
import { ITable } from '@/types/data/table'
import { request } from '@/utils'

export const TABLES_LIST_QUERY_KEY = 'tables-list'

export type TablesListQuery = Partial<TPaginationModel & TSearch> & {
  location?: string
  capacity?: number
  is_active?: number | boolean
  sort_by?: 'table_number' | 'capacity' | 'location' | 'created_at'
  sort_as?: 'asc' | 'desc'
}

export const useGetTablesList = (
  query?: TablesListQuery,
  options?: CustomUseQueryOptions<IBaseResponse<IPaginatedData<ITable[]>>>
) => {
  const queryKey = [TABLES_LIST_QUERY_KEY, query]

  const tablesList = useCustomQuery<IBaseResponse<IPaginatedData<ITable[]>>>(
    queryKey,
    () => {
      const params: Record<string, string> = {}

      const perPage = query?.per_page ?? 20
      params.per_page = String(perPage)

      if (query?.page !== undefined) {
        params.page = String(query.page)
      }

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

          if (key === 'per_page' || key === 'page') {
            return
          }

          params[key] = String(value)
        })
      }

      return request<IBaseResponse<IPaginatedData<ITable[]>>>({
        url: '/tables',
        params
      })
    },
    options
  )

  return tablesList
}
