import { useQuery } from '@tanstack/react-query'
import { Ingredients } from '../../types/services/ingredient'
import { api } from '../api'
import { Ingredient } from '@/types/services/productRecipe'

interface IngredientsQueryParams {
  page?: number
  limit?: number
  search?: string
}

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

  return useQuery<Ingredients>({
    queryKey: ['ingredients', { 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(`/ingredients?${queryParams.toString()}`)
      return res.data.data
    }
  })
}

export function useIngredientById(id: string) {
  return useQuery<Ingredient>({
    queryKey: ['ingredients', id],
    queryFn: async () => {
      const res = await api.get(`/ingredients/${id}`)
      return res.data.data
    }
  })
}
