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

export interface PortCoordinates {
  latitude: number;
  longitude: number;
}

export interface Port {
  id: string;
  code: string;
  name: string;
  city: string;
  country: string;
  countryName: string;
  coordinates: PortCoordinates;
  timezone?: string;
  isActive: boolean;
  displayName: string;
}

export interface PortSearchParams {
  query: string;
  limit?: number;
  countryFilter?: string;
}

export interface PortSearchResponse {
  ports: Port[];
  totalMatches: number;
}

/**
 * Search ports by query (autocomplete)
 */
export async function searchPorts(params: PortSearchParams): Promise<PortSearchResponse> {
  // Use the same key as the rest of the app: 'access_token' with underscore
  const token = typeof window !== 'undefined' ? localStorage.getItem('access_token') : null;
  if (!token) {
    throw new Error('No access token found');
  }

  const queryParams = new URLSearchParams({
    query: params.query,
  });

  if (params.limit) {
    queryParams.append('limit', params.limit.toString());
  }

  if (params.countryFilter) {
    queryParams.append('countryFilter', params.countryFilter);
  }

  const response = await fetch(`${API_BASE_URL}/api/v1/ports/search?${queryParams.toString()}`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Failed to search ports');
  }

  return response.json();
}
