import { z } from 'zod';

/**
 * Core email validation schema and helper types.
 * Kept in domain/types so domain/value-objects can host the EmailAddress VO class.
 */
export const emailSchema = z
  .string()
  .trim()
  .toLowerCase()
  .min(6, 'Email too short')
  .max(254, 'Email too long')
  .email('Invalid email format');

export type EmailValidationSuccess = {
  success: true;
  email: string;
  error?: undefined;
};

export type EmailValidationFailure = {
  success: false;
  email?: undefined;
  error: string;
};

export type EmailValidationResult = EmailValidationSuccess | EmailValidationFailure;

/**
 * Validate and normalize an email address.
 * Mirrors the previous apps/website/lib/email-validation.ts behavior.
 */
export function validateEmail(email: string): EmailValidationResult {
  const result = emailSchema.safeParse(email);

  if (result.success) {
    return {
      success: true,
      email: result.data,
    };
  }

  return {
    success: false,
    error: result.error.errors[0]?.message || 'Invalid email',
  };
}

/**
 * Basic disposable email detection.
 * This list matches the previous website-local implementation and
 * can be extended in the future without changing the public API.
 */
export const DISPOSABLE_DOMAINS = new Set<string>([
  'tempmail.com',
  'throwaway.email',
  'guerrillamail.com',
  'mailinator.com',
  '10minutemail.com',
]);

export function isDisposableEmail(email: string): boolean {
  const domain = email.split('@')[1]?.toLowerCase();
  return domain ? DISPOSABLE_DOMAINS.has(domain) : false;
}