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

/**
 * Value object: a Dutch postcode. "Parse, don't validate" — a Postcode is a
 * distinct type from a raw string, mintable only via parsePostcode, so holding
 * one is proof it is well-formed.
 */
export type Postcode = Brand<string, 'Postcode'>;

export function parsePostcode(raw: string): Result<string, Postcode> {
  const t = raw.trim().toUpperCase();
  if (!/^[1-9]\d{3}\s?[A-Z]{2}$/.test(t)) {
    return err($localize`:@@validation.postcode:Voer een geldige postcode in, bijv. 1234 AB.`);
  }
  // Normalise to "1234 AB" — the parser also cleans up.
  return ok(t.replace(/^(\d{4})\s?([A-Z]{2})$/, '$1 $2') as Postcode);
}
