import { supabase } from '@/integrations/supabase/client';
import { invokeWithTracking } from '@/lib/edgeFunctionTracking';
import { logger } from '@/lib/logger';
import { getErrorMessage } 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) {
      logger.error('Email validation error from backend', {
        action: 'validate_email_backend',
        error: error.message
      });
      return {
        valid: false,
        reason: 'Unable to validate email address. Please try again.'
      };
    }

    return data as EmailValidationResult;
  } catch (error: unknown) {
    const errorMsg = getErrorMessage(error);
    logger.error('Email validation error', {
      action: 'validate_email_disposable',
      error: errorMsg
    });
    return {
      valid: false,
      reason: 'Unable to validate email address. Please try again.'
    };
  }
}
