import { normalizeEmail } from '~/utils/formatters/email'

const EMAIL_VALIDATION_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

export const EMAIL_INPUT_PATTERN = EMAIL_VALIDATION_PATTERN.source

export type EmailValidationResult = {
  valid: boolean
  error?: string
}

export const EMAIL_VALIDATION_ERROR = 'Adresse email invalide'

/**
 * Minimal email schema to align validation logic across the UI.
 */
export const emailSchema = {
  pattern: EMAIL_VALIDATION_PATTERN,
  message: EMAIL_VALIDATION_ERROR,
  validate(value: string): EmailValidationResult {
    const normalized = normalizeEmail(value)
    if (!normalized) {
      return { valid: true }
    }

    if (EMAIL_VALIDATION_PATTERN.test(normalized)) {
      return { valid: true }
    }

    return { valid: false, error: EMAIL_VALIDATION_ERROR }
  },
}

export const isEmailValid = (value: string): boolean => emailSchema.validate(value).valid
