import { Brand, Result, ok, err } from '@shared/kernel/fp';

/**
 * Value object: an e-mail address. "Parse, don't validate" — an Email is a
 * distinct type from a raw string, mintable only via parseEmail, so holding one
 * is proof it is well-formed. Format-only check (the FE keeps format validation
 * for instant feedback; the backend stays the authority — see ADR-0001).
 */
export type Email = Brand<string, 'Email'>;

export function parseEmail(raw: string): Result<string, Email> {
  const t = raw.trim();
  // Deliberately lax: a single @ with non-empty, dot-bearing parts. Good enough
  // for instant feedback; the server re-validates.
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)) {
    return err($localize`:@@validation.email:Voer een geldig e-mailadres in, bijv. naam@voorbeeld.nl.`);
  }
  return ok(t as Email);
}
