/**
 * @ai-summary React hooks for security settings management
 */

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

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

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

  return useQuery({
    queryKey: ['security-status'],
    queryFn: async () => {
      const response = await securityApi.getSecurityStatus();
      return response.data;
    },
    enabled: isAuthenticated && !isLoading,
    staleTime: 5 * 60 * 1000, // 5 minutes
    gcTime: 10 * 60 * 1000, // 10 minutes cache time
    retry: (failureCount, error: ApiError) => {
      if (error?.response?.data?.error === 'Unauthorized' && failureCount < 3) {
        return true;
      }
      return false;
    },
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
    refetchOnWindowFocus: false,
  });
};

export const useRequestPasswordReset = () => {
  return useMutation({
    mutationFn: () => securityApi.requestPasswordReset(),
    onSuccess: (response) => {
      toast.success(response.data.message);
    },
    onError: (error: ApiError) => {
      toast.error(
        error.response?.data?.message ||
        error.response?.data?.error ||
        'Failed to send password reset email'
      );
    },
  });
};
