/**
 * @ai-summary React Query hooks for pending vehicle association management
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useAuth0 } from '@auth0/auth0-react';
import { emailIngestionApi } from '../api/email-ingestion.api';
import toast from 'react-hot-toast';

export const usePendingAssociationCount = () => {
  const { isAuthenticated, isLoading } = useAuth0();

  return useQuery({
    queryKey: ['pendingAssociations', 'count'],
    queryFn: emailIngestionApi.getPendingCount,
    enabled: isAuthenticated && !isLoading,
    staleTime: 60 * 1000,
    refetchInterval: 2 * 60 * 1000,
  });
};

export const usePendingAssociations = () => {
  const { isAuthenticated, isLoading } = useAuth0();

  return useQuery({
    queryKey: ['pendingAssociations'],
    queryFn: emailIngestionApi.getPending,
    enabled: isAuthenticated && !isLoading,
    staleTime: 30 * 1000,
  });
};

export const useResolveAssociation = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ associationId, vehicleId }: { associationId: string; vehicleId: string }) =>
      emailIngestionApi.resolve(associationId, vehicleId),
    onSuccess: (_data) => {
      queryClient.invalidateQueries({ queryKey: ['pendingAssociations'] });
      queryClient.invalidateQueries({ queryKey: ['fuelLogs'] });
      queryClient.invalidateQueries({ queryKey: ['maintenance'] });
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
      toast.success('Receipt assigned to vehicle');
    },
    onError: () => {
      toast.error('Failed to assign receipt');
    },
  });
};

export const useDismissAssociation = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (associationId: string) => emailIngestionApi.dismiss(associationId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['pendingAssociations'] });
      toast.success('Receipt dismissed');
    },
    onError: () => {
      toast.error('Failed to dismiss receipt');
    },
  });
};
