import { useState } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';

export function useRestoreUsers() {
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const syncUsers = async () => {
    setLoading(true);
    try {
      console.log('Invoking restore-users edge function...');
      const { data, error } = await supabase.functions.invoke('restore-users');

      if (error) {
          console.error('Function invocation error:', error);
          throw new Error(error.message || 'Failed to connect to sync service.');
      }

      if (data && data.success === false) {
          throw new Error(data.error || 'Sync operation returned failure status.');
      }

      return {
        success: true,
        restored_count: data.restored_count,
        total_auth_users: data.total_auth_users,
        restored_users_list: data.restored_users_list
      };
    } catch (error) {
      console.error('Error syncing users:', error);
      toast({
        variant: "destructive",
        title: "Sync Failed",
        description: error.message || "An unexpected error occurred while syncing users."
      });
      return { success: false, error: error.message };
    } finally {
      setLoading(false);
    }
  };

  return {
    syncUsers,
    loading
  };
}
