import { useQuery } from '@tanstack/react-query'
import { Product, Products } from '../../types/services/product'
import { api } from '../api'

export interface ProductsQueryParams {
  page?: number
  limit?: number
  search?: string
  // Add other filter parameters as needed
  category_id?: string
  is_active?: boolean | string
}

export function useProducts(params: ProductsQueryParams = {}) {
  const { page = 1, limit = 10, search = '', ...filters } = params

  return useQuery<Products>({
    queryKey: ['products', { page, limit, search, ...filters }],
    queryFn: async () => {
      const queryParams = new URLSearchParams()

      queryParams.append('page', page.toString())
      queryParams.append('limit', limit.toString())

      if (search) {
        queryParams.append('search', search)
      }

      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
          queryParams.append(key, value.toString())
        }
      })

      const res = await api.get(`/products?${queryParams.toString()}`)
      return res.data.data
    },
  })
}

export function useProductById(id: string) {
  return useQuery<Product>({
    queryKey: ['product', id],
    queryFn: async () => {
      const res = await api.get(`/products/${id}`)
      return res.data.data
    },
    staleTime: 5 * 60 * 1000
  })
}
