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

export const trainKeys = {
  all: ['trains'] as const,
  lists: () => [...trainKeys.all, 'list'] as const,
  details: () => [...trainKeys.all, 'detail'] as const,
  detail: (id: string) => [...trainKeys.details(), id] as const,
};

export function useTrains() {
  return useQuery({ queryKey: trainKeys.lists(), queryFn: () => trainService.getAll().then(res => res.data) });
}

export const useGetTrains = useTrains;

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

export const useGetTrain = useTrain;

export function useCreateTrain() {
  const qc = useQueryClient();
  return useMutation({ mutationFn: trainService.create, onSuccess: () => qc.invalidateQueries({ queryKey: trainKeys.lists() }) });
}

export function useUpdateTrain() {
  const qc = useQueryClient();
  return useMutation({ mutationFn: ({ id, data }: any) => trainService.update(id, data), onSuccess: (_, { id }) => {
    qc.invalidateQueries({ queryKey: trainKeys.lists() });
    qc.invalidateQueries({ queryKey: trainKeys.detail(id) });
  } });
}

export function useDeleteTrain() {
  const qc = useQueryClient();
  return useMutation({ mutationFn: trainService.delete, onSuccess: () => qc.invalidateQueries({ queryKey: trainKeys.lists() }) });
}
