import { apiGet } from './client';
import { TownItem } from '@/types';

export const TownApi = {
  /**
   * Fetch all departure and destination towns from backend.
   * Throws error if connection fails. Returns empty array if no towns in database.
   */
  async getTowns(): Promise<TownItem[]> {
    const data = await apiGet<TownItem[]>('towns');
    if (!Array.isArray(data)) {
      return [];
    }
    return data.map((t: any) => ({
      id: t.id,
      name: t.name,
      region: t.region ?? 'Cameroon',
      code: t.code ?? (t.name ? t.name.substring(0, 3).toUpperCase() : ''),
      terminalsCount: t.terminalsCount ?? 0,
    }));
  },
};
