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

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

public sealed class TenantSlug : ValueObject
{
    private static readonly Regex SlugRegex = new(@"^[a-z0-9]+(?:-[a-z0-9]+)*$", RegexOptions.Compiled);

    public string Value { get; }

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

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

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

        if (value.Length < 3)
            throw new ArgumentException("Tenant slug must be at least 3 characters", nameof(value));

        if (value.Length > 50)
            throw new ArgumentException("Tenant slug cannot exceed 50 characters", nameof(value));

        if (!SlugRegex.IsMatch(value))
            throw new ArgumentException("Tenant slug can only contain lowercase letters, numbers, and hyphens", nameof(value));

        // Reserved slugs
        var reservedSlugs = new[] { "www", "api", "admin", "app", "dashboard", "docs", "blog", "support" };
        if (reservedSlugs.Contains(value))
            throw new ArgumentException($"Tenant slug '{value}' is reserved", nameof(value));

        return new TenantSlug(value);
    }

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

    public override string ToString() => Value;

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