/**
 * Companies Hook
 *
 * React hook for fetching available carrier companies
 */

import { useState, useEffect } from 'react';
import { getAvailableCompanies } from '@/lib/api/csv-rates';

interface UseCompaniesResult {
  companies: string[];
  loading: boolean;
  error: string | null;
  refetch: () => Promise<void>;
}

export function useCompanies(): UseCompaniesResult {
  const [companies, setCompanies] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchCompanies = async () => {
    setLoading(true);
    setError(null);

    try {
      const response = await getAvailableCompanies();
      setCompanies(response.companies);
    } catch (err: any) {
      setError(err?.message || 'Failed to fetch companies');
      setCompanies([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCompanies();
  }, []);

  return {
    companies,
    loading,
    error,
    refetch: fetchCompanies,
  };
}
