import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { wagonService } from '@/services/wagon.service';

export const wagonKeys = {
  all: ['wagons'] as const,
  byTrain: (trainId: string) => [...wagonKeys.all, 'train', trainId] as const,
  details: () => [...wagonKeys.all, 'detail'] as const,
  detail: (id: string) => [...wagonKeys.details(), id] as const,
};

export function useWagons() {
  return useQuery({ queryKey: wagonKeys.all, queryFn: () => wagonService.getAll().then(res => res.data) });
}

export const useGetWagons = useWagons;

export function useWagonsByTrain(trainId: string) {
  return useQuery({ queryKey: wagonKeys.byTrain(trainId), queryFn: () => wagonService.getByTrain(trainId).then(res => res.data), enabled: !!trainId });
}

export function useWagon(id: string) {
  return useQuery({ queryKey: wagonKeys.detail(id), queryFn: () => wagonService.getById(id).then(res => res.data), enabled: !!id });
}

export const useGetWagon = useWagon;

export function useAssignWagonToTrain() {
  const qc = useQueryClient();
  return useMutation({ mutationFn: ({ wagonId, trainId, sequenceNumber }: any) => wagonService.assignToTrain(wagonId, trainId, sequenceNumber), onSuccess: (_, { trainId }) => qc.invalidateQueries({ queryKey: wagonKeys.byTrain(trainId) }) });
}

export function useUnassignWagon() {
  const qc = useQueryClient();
  return useMutation({ mutationFn: wagonService.unassign, onSuccess: () => qc.invalidateQueries({ queryKey: wagonKeys.all }) });
}

export function useReorderWagons() {
  const qc = useQueryClient();
  return useMutation({ mutationFn: ({ trainId, wagonIds }: any) => wagonService.reorder(trainId, wagonIds), onSuccess: (_, { trainId }) => qc.invalidateQueries({ queryKey: wagonKeys.byTrain(trainId) }) });
}

export function useCreateWagon() {
  const qc = useQueryClient();
  return useMutation({ mutationFn: wagonService.create, onSuccess: () => qc.invalidateQueries({ queryKey: wagonKeys.all }) });
}

export function useUpdateWagon() {
  const qc = useQueryClient();
  return useMutation({ mutationFn: ({ id, data }: any) => wagonService.update(id, data), onSuccess: (_, { id }) => {
    qc.invalidateQueries({ queryKey: wagonKeys.all });
    qc.invalidateQueries({ queryKey: wagonKeys.detail(id) });
  } });
}

export function useDeleteWagon() {
  const qc = useQueryClient();
  return useMutation({ mutationFn: wagonService.delete, onSuccess: () => qc.invalidateQueries({ queryKey: wagonKeys.all }) });
}
