/**
 * @ai-summary React Query hook for email verification status with polling
 */

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

interface ApiError {
  response?: {
    data?: {
      error?: string;
      message?: string;
    };
  };
  message?: string;
}

export const useVerifyStatus = (options?: { enablePolling?: boolean; onVerified?: () => void }) => {
  const { isAuthenticated, isLoading } = useAuth0();

  const query = useQuery({
    queryKey: ['verifyStatus'],
    queryFn: authApi.getVerifyStatus,
    enabled: isAuthenticated && !isLoading,
    refetchInterval: options?.enablePolling ? 5000 : false, // Poll every 5 seconds if enabled
    refetchIntervalInBackground: false,
    retry: 2,
  });

  // Call onVerified callback when verification completes
  if (query.data?.emailVerified && options?.onVerified) {
    options.onVerified();
  }

  return query;
};

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

  return useMutation({
    mutationFn: () => authApi.resendVerification(),
    onSuccess: (data) => {
      toast.success(data.message || 'Verification email sent. Please check your inbox.');
      queryClient.invalidateQueries({ queryKey: ['verifyStatus'] });
    },
    onError: (error: ApiError) => {
      const errorMessage = error.response?.data?.error || error.response?.data?.message || error.message || 'Failed to resend verification email';
      toast.error(errorMessage);
    },
  });
};

/**
 * Public resend verification - no authentication required
 * Used on the "Check Your Email" page before user can login
 */
export const useResendVerificationPublic = () => {
  return useMutation({
    mutationFn: (email: string) => authApi.resendVerificationPublic({ email }),
    onSuccess: (data) => {
      toast.success(data.message || 'If an account exists, a verification link will be sent.');
    },
    onError: (error: ApiError) => {
      // Always show success message for security (don't reveal if email exists)
      toast.success('If an account exists, a verification link will be sent.');
      console.error('Resend verification error:', error);
    },
  });
};
