import { useQuery } from '@tanstack/react-query'
import { Order, Orders } from '../../types/services/order'
import { api } from '../api'

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

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

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

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