using System.Security.Cryptography;

namespace Flo.Installer.Provisioning;

internal static class PasswordGenerator
{
    private const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    // Largest multiple of 62 that is <= 256; rejection sampling avoids modulo bias.
    private const byte RejectAbove = 247;

    public static string Generate(int length = 32)
    {
        var chars = new char[length];
        Span<byte> b = stackalloc byte[1];
        for (int i = 0; i < length;)
        {
            RandomNumberGenerator.Fill(b);
            if (b[0] <= RejectAbove)
                chars[i++] = Alphabet[b[0] % Alphabet.Length];
        }
        return new string(chars);
    }
}
