using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;

namespace StellaOps.Feedser.Models;

/// <summary>
/// Lightweight validation helpers shared across canonical model constructors.
/// </summary>
public static partial class Validation
{
    public static string EnsureNotNullOrWhiteSpace(string value, string paramName)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            throw new ArgumentException($"Value cannot be null or whitespace.", paramName);
        }

        return value.Trim();
    }

    public static string? TrimToNull(string? value)
        => string.IsNullOrWhiteSpace(value) ? null : value.Trim();

    public static bool LooksLikeHttpUrl(string? value)
        => value is not null && Uri.TryCreate(value, UriKind.Absolute, out var uri) && (uri.Scheme is "http" or "https");

    public static bool TryNormalizeAlias(string? value, [NotNullWhen(true)] out string? normalized)
    {
        normalized = TrimToNull(value);
        if (normalized is null)
        {
            return false;
        }

        if (AliasSchemeRegistry.TryNormalize(normalized, out var canonical, out _))
        {
            normalized = canonical;
        }

        return true;
    }

    public static bool TryNormalizeIdentifier(string? value, [NotNullWhen(true)] out string? normalized)
    {
        normalized = TrimToNull(value);
        return normalized is not null;
    }

    [GeneratedRegex(@"\s+")]
    private static partial Regex CollapseWhitespaceRegex();

    public static string CollapseWhitespace(string value)
    {
        ArgumentNullException.ThrowIfNull(value);
        return CollapseWhitespaceRegex().Replace(value, " ").Trim();
    }
}
