import { api } from "../auth/http";

type ListResponse<T> = T[] | { data: T[] };

export interface TruckType {
  id: string;
  code: string;
  name: string;
  /** Pre-fills a vehicle's capacity — capacity belongs to the type, not each truck. */
  capacityTons: number | null;
  /** False for a rigid truck (e.g. Casoni), which has no trailer plate at all. */
  hasTrailer: boolean;
  description?: string | null;
  isActive: boolean;
}

const asList = <T>(payload: ListResponse<T>): T[] =>
  Array.isArray(payload) ? payload : payload.data;

export const truckTypesService = {
  async getTruckTypes() {
    const response = await api.get<ListResponse<TruckType>>('/truck-types', {
      params: { isActive: 'all', pageSize: 500 },
    });
    return asList(response.data);
  },
  create: (data: Partial<TruckType>) => api.post('/truck-types', data),
  update: (id: string, data: Partial<TruckType>) => api.patch(`/truck-types/${id}`, data),
  delete: (id: string) => api.delete(`/truck-types/${id}`),
};
