using System.Text.RegularExpressions;
namespace New.Domain.ValueObjects;
/// How the applicant prefers to be contacted.
public enum CorrespondenceChannel
{
Post,
Email,
}
///
/// Email/phone plus the applicant's preferred channel. The one real invariant:
/// choosing requires a non-empty,
/// well-formed email address - you can't ask to be emailed with no email on file.
///
public sealed record ContactDetails
{
private static readonly Regex SimpleEmailPattern =
new(@"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.Compiled);
public string? Email { get; }
public string? Phone { get; }
public CorrespondenceChannel PreferredChannel { get; }
public ContactDetails(string? email, string? phone, CorrespondenceChannel preferredChannel)
{
if (preferredChannel == CorrespondenceChannel.Email && !IsWellFormedEmail(email))
{
throw new DomainInvariantViolationException(
"ContactDetails.EmailRequiredForEmailChannel",
"Preferring email as the correspondence channel requires a non-empty, well-formed email address.");
}
Email = email;
Phone = phone;
PreferredChannel = preferredChannel;
}
private static bool IsWellFormedEmail(string? email) =>
!string.IsNullOrWhiteSpace(email) && SimpleEmailPattern.IsMatch(email);
}