/**
 * CSV Rates API Client
 *
 * Client for CSV-based rate search endpoints
 */

import {
  CsvRateSearchRequest,
  CsvRateSearchResponse,
  AvailableCompanies,
  FilterOptions,
} from '@/types/rate-filters';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000';

/**
 * Get authentication token from localStorage
 */
function getAuthToken(): string | null {
  if (typeof window === 'undefined') return null;
  return localStorage.getItem('access_token');
}

/**
 * Create headers with authentication
 */
function createHeaders(): HeadersInit {
  const headers: HeadersInit = {
    'Content-Type': 'application/json',
  };

  const token = getAuthToken();
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  return headers;
}

/**
 * Search CSV-based rates with filters
 */
export async function searchCsvRates(
  request: CsvRateSearchRequest
): Promise<CsvRateSearchResponse> {
  const response = await fetch(`${API_BASE_URL}/api/v1/rates/search-csv`, {
    method: 'POST',
    headers: createHeaders(),
    body: JSON.stringify(request),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({}));
    throw new Error(error.message || `Failed to search CSV rates: ${response.statusText}`);
  }

  return response.json();
}

/**
 * Get available carrier companies
 */
export async function getAvailableCompanies(): Promise<AvailableCompanies> {
  const response = await fetch(`${API_BASE_URL}/api/v1/rates/companies`, {
    method: 'GET',
    headers: createHeaders(),
  });

  if (!response.ok) {
    throw new Error(`Failed to fetch companies: ${response.statusText}`);
  }

  return response.json();
}

/**
 * Get available filter options
 */
export async function getFilterOptions(): Promise<FilterOptions> {
  const response = await fetch(`${API_BASE_URL}/api/v1/rates/filters/options`, {
    method: 'GET',
    headers: createHeaders(),
  });

  if (!response.ok) {
    throw new Error(`Failed to fetch filter options: ${response.statusText}`);
  }

  return response.json();
}
