// Email validation using Rapid Email Validator API
// API: https://rapid-email-verifier.fly.dev/
// Privacy-focused, no data storage, completely free

type EmailValidationResult = {
  valid: boolean;
  email: string;
  domain?: string;
  disposable?: boolean;
  role?: boolean;
  typo?: boolean;
  suggestion?: string;
  mx?: boolean;
  error?: string;
};

/**
 * Validate email address using Rapid Email Validator API
 * Returns true if email is valid, false otherwise
 */
export async function validateEmail(email: string): Promise<{
  valid: boolean;
  reason?: string;
  suggestion?: string;
}> {
  try {
    // Call Rapid Email Validator API
    const response = await fetch(`https://rapid-email-verifier.fly.dev/verify/${encodeURIComponent(email)}`, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
      },
    });

    if (!response.ok) {
      console.warn(`Email validation API error: ${response.status}`);
      // If API is down, allow the email (fallback to Zod validation only)
      return { valid: true };
    }

    const data: EmailValidationResult = await response.json();

    // Check if email is disposable/temporary
    if (data.disposable) {
      return {
        valid: false,
        reason: 'Temporäre oder Wegwerf-E-Mail-Adressen sind nicht erlaubt. Bitte verwende eine echte E-Mail-Adresse.',
      };
    }

    // Check if MX records exist (deliverable)
    if (data.mx === false) {
      return {
        valid: false,
        reason: 'Diese E-Mail-Adresse kann keine E-Mails empfangen. Bitte überprüfe deine E-Mail-Adresse.',
      };
    }

    // Check if email is generally valid
    if (!data.valid) {
      const suggestion = data.suggestion ? ` Meintest du vielleicht: ${data.suggestion}?` : '';
      return {
        valid: false,
        reason: `Ungültige E-Mail-Adresse.${suggestion}`,
        suggestion: data.suggestion,
      };
    }

    // Email is valid
    return { valid: true };

  } catch (error) {
    console.error('Email validation error:', error);
    // If validation fails, allow the email (fallback to Zod validation only)
    // This ensures the booking system continues to work even if the API is down
    return { valid: true };
  }
}

/**
 * Batch validate multiple emails
 * @param emails Array of email addresses to validate
 * @returns Array of validation results
 */
export async function validateEmailBatch(emails: string[]): Promise<Map<string, {
  valid: boolean;
  reason?: string;
  suggestion?: string;
}>> {
  const results = new Map<string, { valid: boolean; reason?: string; suggestion?: string }>();

  // Validate up to 100 emails at once (API limit)
  const batchSize = 100;
  for (let i = 0; i < emails.length; i += batchSize) {
    const batch = emails.slice(i, i + batchSize);
    
    // Call each validation in parallel for better performance
    const validations = await Promise.all(
      batch.map(async (email) => {
        const result = await validateEmail(email);
        return { email, result };
      })
    );

    // Store results
    validations.forEach(({ email, result }) => {
      results.set(email, result);
    });
  }

  return results;
}


