import { apiClient } from '@/lib/api-client';
import { Route, Trip, FareRule } from '@/types';
import { PaginatedResponse } from '@edr/types';

export const routesApi = {
  getAll: async () => {
    const response = await apiClient.get<any>('/routes');
    console.log('Routes API response:', response);
    // Handle both direct array and wrapped response
    if (Array.isArray(response)) {
      return { items: response };
    }
    if (response?.data && Array.isArray(response.data)) {
      return { items: response.data };
    }
    if (response?.items) {
      return response;
    }
    return { items: response || [] };
  },

  getById: (id: string) => {
    return apiClient.get<Route>(`/routes/${id}`);
  },

  create: (data: any) => {
    console.log('Creating route with data:', JSON.stringify(data, null, 2));
    return apiClient.post<Route>('/routes', data);
  },

  update: (id: string, data: Partial<Route>) => {
    return apiClient.patch<Route>(`/routes/${id}`, data);
  },

  delete: (id: string) => {
    return apiClient.delete(`/routes/${id}`);
  },

  getFareRules: (routeId: string) => {
    return apiClient.get<FareRule[]>(`/routes/${routeId}/fare-rules`);
  },

  updateFareRule: (routeId: string, ruleId: string, data: Partial<FareRule>) => {
    return apiClient.patch<FareRule>(`/routes/${routeId}/fare-rules/${ruleId}`, data);
  },
};

export const tripsApi = {
  getAll: (filters?: any) => {
    const params = new URLSearchParams();
    if (filters?.status) params.append('status', filters.status);
    if (filters?.date) params.append('date', filters.date);
    
    return apiClient.get<PaginatedResponse<Trip>>(`/schedules?${params.toString()}`);
  },

  getById: (id: string) => {
    return apiClient.get<Trip>(`/schedules/${id}`);
  },

  updateStatus: (id: string, status: string) => {
    return apiClient.patch<Trip>(`/schedules/${id}/status`, { status });
  },
};
