using System.Security.Cryptography;

namespace QYZH.InteractiveMagazine.Common.Helpers;

/// <summary>
/// 随机ID帮助类
/// </summary>
public static class RandomIdHelper
{
    private const long DefaultMinValue = 1_000_000_000_000L;
    private const long DefaultMaxValue = 9_000_000_000_000_000L;

    /// <summary>
    /// 生成不可预测的正数长整型ID
    /// </summary>
    public static long GenerateLongId(long minValue = DefaultMinValue, long maxValue = DefaultMaxValue)
    {
        if (minValue <= 0 || minValue >= maxValue)
        {
            throw new ArgumentOutOfRangeException(nameof(minValue), "随机ID范围配置错误");
        }

        var range = (ulong)(maxValue - minValue);
        var limit = ulong.MaxValue - (ulong.MaxValue % range);

        Span<byte> bytes = stackalloc byte[sizeof(ulong)];
        while (true)
        {
            RandomNumberGenerator.Fill(bytes);
            var value = BitConverter.ToUInt64(bytes);
            if (value < limit)
            {
                return minValue + (long)(value % range);
            }
        }
    }
}
