/**
 * CSV Rate Search Hook
 *
 * React hook for searching CSV-based rates with service level offers
 * (ECONOMIC / STANDARD / RAPID).
 */

import { useState } from 'react';
import { searchCsvRatesWithOffers } from '@/lib/api/rates';
import type { CsvRateSearchRequest, CsvRateSearchResponse } from '@/types/rates';

interface UseCsvRateSearchResult {
  data: CsvRateSearchResponse | null;
  loading: boolean;
  error: string | null;
  search: (request: CsvRateSearchRequest) => Promise<void>;
  reset: () => void;
}

export function useCsvRateSearch(): UseCsvRateSearchResult {
  const [data, setData] = useState<CsvRateSearchResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const search = async (request: CsvRateSearchRequest) => {
    setLoading(true);
    setError(null);

    try {
      const response = await searchCsvRatesWithOffers(request);
      setData(response as unknown as CsvRateSearchResponse);
    } catch (err: any) {
      setError(err?.message || 'Erreur lors de la recherche de tarifs');
      setData(null);
    } finally {
      setLoading(false);
    }
  };

  const reset = () => {
    setData(null);
    setError(null);
    setLoading(false);
  };

  return { data, loading, error, search, reset };
}
