import { PurchaseOrder, PurchaseOrders } from '@/types/services/purchaseOrder'
import { useQuery } from '@tanstack/react-query'
import { api } from '../api'

interface PurchaseOrderQueryParams {
  page?: number
  limit?: number
  search?: string
  status?: string
}

export function usePurchaseOrders(params: PurchaseOrderQueryParams = {}) {
  const { page = 1, limit = 10, search = '', status = '', ...filters } = params

  return useQuery<PurchaseOrders>({
    queryKey: ['purchase-orders', { page, limit, search, status, ...filters }],
    queryFn: async () => {
      const queryParams = new URLSearchParams()

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

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

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

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

      const res = await api.get(`/purchase-orders?${queryParams.toString()}`)
      return res.data.data
    }
  })
}

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