namespace Books.Api.Domain.Companies;

/// <summary>
/// Validates Danish CVR (Central Business Register) numbers.
/// CVR numbers are 8 digits with a modulus 11 checksum.
/// </summary>
public static class CvrValidator
{
    private static readonly int[] Weights = [2, 7, 6, 5, 4, 3, 2, 1];

    /// <summary>
    /// Validates a CVR number using the modulus 11 algorithm.
    /// </summary>
    /// <param name="cvr">The CVR number to validate</param>
    /// <returns>True if valid, false otherwise</returns>
    public static bool IsValid(string? cvr)
    {
        if (string.IsNullOrWhiteSpace(cvr))
            return false;

        // Must be exactly 8 digits
        if (cvr.Length != 8 || !cvr.All(char.IsDigit))
            return false;

        // Modulus 11 check
        var sum = cvr.Select((c, i) => (c - '0') * Weights[i]).Sum();
        return sum % 11 == 0;
    }

    /// <summary>
    /// Validates CVR format (8 digits) without checksum verification.
    /// Useful for displaying format errors before checksum errors.
    /// </summary>
    public static bool HasValidFormat(string? cvr)
    {
        if (string.IsNullOrWhiteSpace(cvr))
            return false;

        return cvr.Length == 8 && cvr.All(char.IsDigit);
    }
}
