// =============================================================================
// 🏢 ХУК ДЛЯ ПОЛУЧЕНИЯ ДАННЫХ ПОСТАВЩИКОВ И ФУЛФИЛМЕНТ-ЦЕНТРОВ (ДЛЯ СЕЛЛЕРА)
// =============================================================================

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

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

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

interface UseSellerSupplierDataProps {
  searchQuery: string
}

interface UseSellerSupplierDataReturn {
  // Поставщики (WHOLESALE)
  suppliers: SellerConsumableSupplier[]
  filteredSuppliers: SellerConsumableSupplier[]
  
  // Фулфилмент-центры (FULFILLMENT)
  fulfillmentCenters: SellerConsumableSupplier[]
  filteredFulfillmentCenters: SellerConsumableSupplier[]
  
  // Логистические партнеры (LOGIST)
  logisticsPartners: SellerConsumableSupplier[]
  
  // Состояние загрузки и ошибки
  loading: boolean
  error: Error | null
}

export function useSellerSupplierData({ 
  searchQuery, 
}: UseSellerSupplierDataProps): UseSellerSupplierDataReturn {
  
  // 🔄 ЗАГРУЗКА КОНТРАГЕНТОВ
  const { data, loading, error } = useQuery<CounterpartiesData>(GET_MY_COUNTERPARTIES)

  // 📊 МЕМОИЗИРОВАННАЯ ОБРАБОТКА ДАННЫХ
  const processedData = useMemo(() => {
    const allPartners = data?.myCounterparties || []
    
    // 🏪 ПОСТАВЩИКИ (где селлер заказывает товары)
    const suppliers = allPartners.filter(partner => partner.type === 'WHOLESALE')
    
    // 🏢 ФУЛФИЛМЕНТ-ЦЕНТРЫ (куда селлер доставляет товары)
    const fulfillmentCenters = allPartners.filter(partner => partner.type === 'FULFILLMENT')
    
    // 🚚 ЛОГИСТИЧЕСКИЕ ПАРТНЕРЫ (кто доставляет)
    const logisticsPartners = allPartners.filter(partner => partner.type === 'LOGIST')

    // 🔍 ФИЛЬТРАЦИЯ ПО ПОИСКУ
    const searchLower = searchQuery.toLowerCase().trim()
    
    const filteredSuppliers = searchLower
      ? suppliers.filter(supplier => 
          supplier.name?.toLowerCase().includes(searchLower) ||
          supplier.fullName?.toLowerCase().includes(searchLower) ||
          supplier.inn.includes(searchLower),
        )
      : suppliers
      
    const filteredFulfillmentCenters = searchLower
      ? fulfillmentCenters.filter(ff => 
          ff.name?.toLowerCase().includes(searchLower) ||
          ff.fullName?.toLowerCase().includes(searchLower) ||
          ff.inn.includes(searchLower),
        )
      : fulfillmentCenters

    return {
      suppliers,
      fulfillmentCenters,
      logisticsPartners,
      filteredSuppliers,
      filteredFulfillmentCenters,
    }
  }, [data?.myCounterparties, searchQuery])

  return {
    ...processedData,
    loading,
    error: error || null,
  }
}