import { supabase } from '@/lib/supabaseClient';
import { invokeWithTracking } from '@/lib/edgeFunctionTracking';
import { handleNonCriticalError } from '@/lib/errorHandler';

interface EmailValidationResult {
  valid: boolean;
  reason?: string;
  suggestions?: string[];
}

/**
 * Validates an email address against disposable email domains
 * Uses the validate-email-backend edge function for server-side validation
 */
export async function validateEmailNotDisposable(email: string): Promise<EmailValidationResult> {
  try {
    const { data, error } = await invokeWithTracking(
      'validate-email-backend',
      { email },
      undefined
    );

    if (error) {
      handleNonCriticalError(error, {
        action: 'Validate email backend',
      });
      return {
        valid: false,
        reason: 'Unable to validate email address. Please try again.'
      };
    }

    return data as EmailValidationResult;
  } catch (error: unknown) {
    handleNonCriticalError(error, {
      action: 'Validate email disposable',
    });
    return {
      valid: false,
      reason: 'Unable to validate email address. Please try again.'
    };
  }
}
