using System.Text.RegularExpressions;
using ColaFlow.Shared.Kernel.Common;

namespace ColaFlow.Modules.Identity.Domain.Aggregates.Users;

public sealed class Email : ValueObject
{
    private static readonly Regex EmailRegex = new(
        @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$",
        RegexOptions.Compiled);

    public string Value { get; }

    private Email(string value)
    {
        Value = value;
    }

    public static Email Create(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
            throw new ArgumentException("Email cannot be empty", nameof(value));

        value = value.ToLowerInvariant().Trim();

        if (value.Length > 255)
            throw new ArgumentException("Email cannot exceed 255 characters", nameof(value));

        if (!EmailRegex.IsMatch(value))
            throw new ArgumentException("Invalid email format", nameof(value));

        return new Email(value);
    }

    protected override IEnumerable<object> GetAtomicValues()
    {
        yield return Value;
    }

    public override string ToString() => Value;

    // Implicit conversion
    public static implicit operator string(Email email) => email.Value;
}
