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

export const CARGOES_QUERY_KEY = ['cargoes'];

export function useCargoes() {
  return useQuery({
    queryKey: CARGOES_QUERY_KEY,
    queryFn: () => cargoService.getCargoes(),
  });
}

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

  const createCargo = useMutation({
    mutationFn: (data: any) => cargoService.createCargo(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: CARGOES_QUERY_KEY });
      toast.success('Cargo created successfully');
    },
  });

  const updateCargo = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) => cargoService.updateCargo(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: CARGOES_QUERY_KEY });
      toast.success('Cargo updated successfully');
    },
  });

  const deleteCargo = useMutation({
    mutationFn: (id: string) => cargoService.deleteCargo(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: CARGOES_QUERY_KEY });
      toast.success('Cargo deleted successfully');
    },
  });

  return { createCargo, updateCargo, deleteCargo };
}