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

export const WAGONS_QUERY_KEY = ['wagons'];

export function useWagons() {
  return useQuery({
    queryKey: WAGONS_QUERY_KEY,
    queryFn: () => wagonService.getWagons(),
  });
}

export function useWagonMutations() {
  const queryClient = useQueryClient();

  const createWagon = useMutation({
    mutationFn: (data: any) => wagonService.createWagon(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: WAGONS_QUERY_KEY });
      toast.success('Wagon created successfully');
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.message || 'Failed to create wagon');
    },
  });

  const updateWagon = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) => wagonService.updateWagon(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: WAGONS_QUERY_KEY });
      toast.success('Wagon updated successfully');
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.message || 'Failed to update wagon');
    },
  });

  const deleteWagon = useMutation({
    mutationFn: (id: string) => wagonService.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: WAGONS_QUERY_KEY });
      toast.success('Wagon deleted successfully');
    },
  });

  return { createWagon, updateWagon, deleteWagon };
}