import { api } from './client';
import type {
  ApiResponse,
  Vehicle,
  VehicleFilters,
  PaginatedResult,
  VehicleType,
  VehicleStatus,
} from '../../types';

export interface CreateVehicleRequest {
  customerId: string;
  fleetId?: string;
  vin?: string;
  licensePlate: string;
  economicNumber?: string;
  make: string;
  model: string;
  year: number;
  color?: string;
  vehicleType?: VehicleType;
  currentOdometer?: number;
  photoUrl?: string;
  notes?: string;
}

export interface UpdateVehicleRequest {
  fleetId?: string | null;
  vin?: string;
  licensePlate?: string;
  economicNumber?: string;
  make?: string;
  model?: string;
  year?: number;
  color?: string;
  vehicleType?: VehicleType;
  currentOdometer?: number;
  photoUrl?: string | null;
  status?: VehicleStatus;
  notes?: string;
}

export const vehiclesApi = {
  list: (filters?: VehicleFilters) => {
    const params = new URLSearchParams();
    if (filters?.vehicleType) params.append('vehicleType', filters.vehicleType);
    if (filters?.customerId) params.append('customerId', filters.customerId);
    if (filters?.status) params.append('status', filters.status);
    if (filters?.search) params.append('search', filters.search);
    if (filters?.page) params.append('page', String(filters.page));
    if (filters?.pageSize) params.append('limit', String(filters.pageSize));

    return api.get<ApiResponse<PaginatedResult<Vehicle>>>(`/vehicles?${params.toString()}`);
  },

  getById: (id: string) =>
    api.get<ApiResponse<Vehicle>>(`/vehicles/${id}`),

  create: (data: CreateVehicleRequest) =>
    api.post<ApiResponse<Vehicle>>('/vehicles', data),

  update: (id: string, data: UpdateVehicleRequest) =>
    api.patch<ApiResponse<Vehicle>>(`/vehicles/${id}`, data),

  delete: (id: string) =>
    api.delete<ApiResponse<null>>(`/vehicles/${id}`),

  // Get service history for a vehicle
  getServiceHistory: (vehicleId: string) =>
    api.get<ApiResponse<{ orders: unknown[] }>>(`/vehicles/${vehicleId}/service-history`),
};
