import { api as apiClient } from '../auth/http';

import { URL_CONSTANTS } from '@/constants/URLS';

export type LocomotiveType = 'DIESEL' | 'ELECTRIC';
export type LocomotiveStatus =
  | 'AVAILABLE'
  | 'UNAVAILABLE'
  | 'IMPORT_READY'
  | 'EXPORT_READY'
  | 'MAINTENANCE'
  | 'ASSIGNED'
  | 'OUT_OF_SERVICE';

export interface LocomotiveListFilters {
  status?: LocomotiveStatus;
  currentYardId?: string;
}

export interface Locomotive {
  id: string;
  code: string;
  name?: string | null;
  locomotiveType: LocomotiveType;
  status: LocomotiveStatus;
  currentYardId: string | null;
  currentYard?: { id: string; label?: string; code?: string } | null;
  maxPullWeightTons: number;
  maxTrainLengthMeters: number;
  powerKw?: number | null;
  tractionForceKn?: number | null;
  maxSpeedKmh?: number | null;
  createdAt: string;
  updatedAt: string;
}

export type SaveLocomotivePayload = Omit<
  Locomotive,
  'id' | 'createdAt' | 'updatedAt'
>;

export const locomotivesService = {
  getAll: (filters: LocomotiveListFilters = {}) => {
    const params = new URLSearchParams();
    if (filters.status) params.set('status', filters.status);
    if (filters.currentYardId) params.set('currentYardId', filters.currentYardId);
    const qs = params.toString();
    return apiClient.get<Locomotive[]>(
      `${URL_CONSTANTS.LOCOMOTIVES.BASE}${qs ? `?${qs}` : ''}`,
    );
  },
  getById: (id: string) => apiClient.get<Locomotive>(URL_CONSTANTS.LOCOMOTIVES.BY_ID(id)),
  create: (data: Partial<SaveLocomotivePayload>) =>
    apiClient.post(URL_CONSTANTS.LOCOMOTIVES.BASE, data),
  update: (id: string, data: Partial<SaveLocomotivePayload>) =>
    apiClient.patch(URL_CONSTANTS.LOCOMOTIVES.BY_ID(id), data),
  decommission: (id: string) => apiClient.post(URL_CONSTANTS.LOCOMOTIVES.DECOMMISSION(id), {}),
};
