/**
 * React Query hooks for custom domain management
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  getCustomDomains,
  addCustomDomain,
  deleteCustomDomain,
  verifyCustomDomain,
  setPrimaryDomain,
} from '../api/customDomains';
import { CustomDomain } from '../types';

/**
 * Hook to fetch all custom domains for the current business
 */
export const useCustomDomains = () => {
  return useQuery<CustomDomain[], Error>({
    queryKey: ['customDomains'],
    queryFn: getCustomDomains,
    retry: false, // Don't retry on 404
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
};

/**
 * Hook to add a new custom domain
 */
export const useAddCustomDomain = () => {
  const queryClient = useQueryClient();

  return useMutation<CustomDomain, Error, string>({
    mutationFn: addCustomDomain,
    onSuccess: () => {
      // Invalidate and refetch custom domains
      queryClient.invalidateQueries({ queryKey: ['customDomains'] });
    },
  });
};

/**
 * Hook to delete a custom domain
 */
export const useDeleteCustomDomain = () => {
  const queryClient = useQueryClient();

  return useMutation<void, Error, number>({
    mutationFn: deleteCustomDomain,
    onSuccess: () => {
      // Invalidate and refetch custom domains
      queryClient.invalidateQueries({ queryKey: ['customDomains'] });
    },
  });
};

/**
 * Hook to verify a custom domain
 */
export const useVerifyCustomDomain = () => {
  const queryClient = useQueryClient();

  return useMutation<{ verified: boolean; message: string }, Error, number>({
    mutationFn: verifyCustomDomain,
    onSuccess: () => {
      // Invalidate and refetch custom domains
      queryClient.invalidateQueries({ queryKey: ['customDomains'] });
    },
  });
};

/**
 * Hook to set a custom domain as primary
 */
export const useSetPrimaryDomain = () => {
  const queryClient = useQueryClient();

  return useMutation<CustomDomain, Error, number>({
    mutationFn: setPrimaryDomain,
    onSuccess: () => {
      // Invalidate and refetch custom domains
      queryClient.invalidateQueries({ queryKey: ['customDomains'] });
    },
  });
};
