/**
 * @ai-summary React Query hooks for onboarding flow
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useAuth0 } from '@auth0/auth0-react';
import toast from 'react-hot-toast';
import { onboardingApi } from '../api/onboarding.api';
import { OnboardingPreferences } from '../types/onboarding.types';

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

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

  return useQuery({
    queryKey: ['onboarding-status'],
    queryFn: onboardingApi.getStatus,
    enabled: isAuthenticated && !isLoading,
    staleTime: 5 * 60 * 1000, // 5 minutes
    retry: false,
  });
};

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

  return useMutation({
    mutationFn: (data: OnboardingPreferences) => onboardingApi.savePreferences(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['onboarding-status'] });
      toast.success('Preferences saved successfully');
    },
    onError: (error: ApiError) => {
      const errorMessage = error.response?.data?.error || error.message || 'Failed to save preferences';
      toast.error(errorMessage);
    },
  });
};

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

  return useMutation({
    mutationFn: onboardingApi.completeOnboarding,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['onboarding-status'] });
    },
    onError: (error: ApiError) => {
      const errorMessage = error.response?.data?.error || error.message || 'Failed to complete onboarding';
      toast.error(errorMessage);
    },
  });
};
