import type { Freight } from "@edr/types";

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

export interface Wagon {
  id: string;
  wagonNumber: string;
  wagonTypeId: string;
  trainId: string | null;
  sequenceNumber: number | null;
  currentLocationYardId: string | null;
  currentLocationYard?: {
    id: string;
    code: string;
    label: string;
    country?: string;
  } | null;
  wagonType?: {
    id: string;
    code: string;
    name: string;
    supportedLoadTypes?: string[];
  } | null;
  tareWeight: number;
  maxPayloadWeight: number;
  status: Freight.WagonStatus;
  currentYardId: string | null;
  currentYard?: { id: string; label?: string; code?: string } | null;
  notes?: string;
}

export interface WagonListFilters {
  search?: string;
  status?: Freight.WagonStatus;
  currentYardId?: string;
  wagonTypeId?: string;
  trainId?: string;
}

export const wagonService = {
  getAll: (filters: WagonListFilters = {}) => {
    const params = new URLSearchParams();
    if (filters.search?.trim()) params.set('search', filters.search.trim());
    if (filters.status) params.set('status', filters.status);
    if (filters.currentYardId) params.set('currentYardId', filters.currentYardId);
    if (filters.wagonTypeId) params.set('wagonTypeId', filters.wagonTypeId);
    if (filters.trainId) params.set('trainId', filters.trainId);
    const qs = params.toString();
    return apiClient.get<Wagon[]>(`/wagons${qs ? `?${qs}` : ''}`);
  },
  getById: (id: string) => apiClient.get<Wagon>(`/wagons/${id}`),
  getByTrain: (trainId: string) => apiClient.get<Wagon[]>(`/wagons?trainId=${trainId}`),
  assignToTrain: (wagonId: string, trainId: string, sequenceNumber?: number) =>
    apiClient.post(`/wagons/${wagonId}/assign-train`, { trainId, sequenceNumber }),
  unassign: (wagonId: string) => apiClient.post(`/wagons/${wagonId}/unassign-train`),
  reorder: (trainId: string, wagonIds: string[]) =>
    apiClient.post(`/trains/${trainId}/reorder-wagons`, { wagonIds }),
  create: (data: Partial<Wagon>) => apiClient.post('/wagons', data),
  update: (id: string, data: Partial<Wagon>) => apiClient.patch(`/wagons/${id}`, data),
  delete: (id: string) => apiClient.delete(`/wagons/${id}`),
};
