import { api as apiClient } from '../auth/http';
import { URL_CONSTANTS } from '@/constants/URLS';

export type VehicleType = 'TRUCK' | 'VAN' | 'CAR' | 'BUS' | 'TRAILER' | 'TANKER' | 'FLATBED';
export type FuelType = 'PETROL' | 'DIESEL' | 'ELECTRIC' | 'HYBRID';
export type VehicleStatus = 'ACTIVE' | 'MAINTENANCE' | 'RETIRED' | 'OUT_OF_SERVICE';

export interface VehicleListFilters {
  status?: VehicleStatus;
  search?: string;
  page?: number;
  limit?: number;
  sortBy?: string;
  sortOrder?: 'ASC' | 'DESC';
}

export interface Vehicle {
  id: string;
  plateNumber: string;
  registrationNumber: string;
  vehicleType: VehicleType;
  manufacturer: string;
  model: string;
  year: number;
  fuelType: FuelType;
  capacity: number;
  status: VehicleStatus;
  description?: string | null;
  createdAt: string;
  updatedAt: string;
}

export type SaveVehiclePayload = Omit<
  Vehicle,
  'id' | 'createdAt' | 'updatedAt' | 'registrationNumber'
>;

export const vehiclesService = {
  getAll: (filters: VehicleListFilters = {}) => {
    const params = new URLSearchParams();
    if (filters.status) params.set('status', filters.status);
    if (filters.search) params.set('search', filters.search);
    if (filters.page) params.set('page', filters.page.toString());
    if (filters.limit) params.set('limit', filters.limit.toString());
    if (filters.sortBy) params.set('sortBy', filters.sortBy);
    if (filters.sortOrder) params.set('sortOrder', filters.sortOrder);
    const qs = params.toString();
    return apiClient.get<Vehicle[]>(
      `${URL_CONSTANTS.VEHICLES.BASE}${qs ? `?${qs}` : ''}`,
    );
  },
  getById: (id: string) => apiClient.get<Vehicle>(URL_CONSTANTS.VEHICLES.BY_ID(id)),
  create: (data: Partial<SaveVehiclePayload>) =>
    apiClient.post(URL_CONSTANTS.VEHICLES.BASE, data),
  update: (id: string, data: Partial<SaveVehiclePayload>) =>
    apiClient.patch(URL_CONSTANTS.VEHICLES.BY_ID(id), data),
  delete: (id: string) => apiClient.delete(URL_CONSTANTS.VEHICLES.BY_ID(id)),
};
