// =============================================================================
// 🏢 ХУК ДЛЯ УПРАВЛЕНИЯ ДАННЫМИ ПОСТАВЩИКОВ
// =============================================================================

import { useQuery } from '@apollo/client'
import { useMemo } from 'react'

import { GET_MY_COUNTERPARTIES } from '@/graphql/queries'

import type { 
  FulfillmentConsumableSupplier, 
  CounterpartiesData,
  UseSupplierDataReturn, 
} from '../types'

interface UseSupplierDataProps {
  searchQuery: string
}

export function useSupplierData({ searchQuery }: UseSupplierDataProps): UseSupplierDataReturn {
  // Загружаем контрагентов-поставщиков расходников
  const { data, loading, error } = useQuery<CounterpartiesData>(GET_MY_COUNTERPARTIES)

  // Фильтруем только поставщиков расходников (WHOLESALE)
  const suppliers = useMemo(() => {
    return (data?.myCounterparties || []).filter(
      (org: FulfillmentConsumableSupplier) => org.type === 'WHOLESALE',
    )
  }, [data?.myCounterparties])

  // Фильтруем только логистические компании (LOGIST)
  const logisticsPartners = useMemo(() => {
    return (data?.myCounterparties || []).filter(
      (org: FulfillmentConsumableSupplier) => org.type === 'LOGIST',
    )
  }, [data?.myCounterparties])

  // Фильтруем поставщиков по поисковому запросу
  const filteredSuppliers = useMemo(() => {
    if (!searchQuery.trim()) {
      return suppliers
    }

    const query = searchQuery.toLowerCase()
    return suppliers.filter((supplier: FulfillmentConsumableSupplier) =>
      supplier.name?.toLowerCase().includes(query) ||
      supplier.fullName?.toLowerCase().includes(query) ||
      supplier.inn?.toLowerCase().includes(query),
    )
  }, [suppliers, searchQuery])

  return {
    suppliers,
    logisticsPartners,
    filteredSuppliers,
    loading,
    error: error || null,
  }
}