using System.Globalization;
using System.Security.Cryptography;
using System.Text.RegularExpressions;

namespace YMhut.Box.Core.Feedback;

public static class FeedbackCode
{
    private static readonly Regex Pattern = new(
        "^FB-[0-9]{8}-[A-F0-9]{6}$",
        RegexOptions.Compiled | RegexOptions.CultureInvariant);

    public static string Create(DateTimeOffset? now = null)
    {
        Span<byte> bytes = stackalloc byte[3];
        RandomNumberGenerator.Fill(bytes);
        var stamp = (now ?? DateTimeOffset.Now).ToString("yyyyMMdd", CultureInfo.InvariantCulture);
        return $"FB-{stamp}-{Convert.ToHexString(bytes)}";
    }

    public static bool IsValid(string? value)
    {
        return Pattern.IsMatch(Normalize(value));
    }

    public static string Normalize(string? value)
    {
        return string.IsNullOrWhiteSpace(value)
            ? string.Empty
            : value.Trim().ToUpperInvariant();
    }
}
