using System.Security.Cryptography;
using System.Text;

namespace ZB.MOM.WW.ScadaBridge.Commons.Types.Deployment;

/// <summary>
/// Generates and compares the single-purpose, short-TTL token that authorizes a
/// site's HTTP fetch of one deployment's flattened config. URL-safe; compared in
/// constant time to avoid timing oracles.
/// </summary>
public static class DeploymentFetchToken
{
    /// <summary>Generates a URL-safe random token (256 bits of entropy).</summary>
    /// <returns>A URL-safe, base64-encoded random token string.</returns>
    public static string Generate() =>
        Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))
               .Replace('+', '-').Replace('/', '_').TrimEnd('=');

    /// <summary>Constant-time string comparison (no early-out on first mismatch).</summary>
    /// <param name="a">The first string to compare.</param>
    /// <param name="b">The second string to compare.</param>
    /// <returns><see langword="true"/> if the strings are equal; otherwise <see langword="false"/>.</returns>
    public static bool ConstantTimeEquals(string a, string b) =>
        CryptographicOperations.FixedTimeEquals(
            Encoding.UTF8.GetBytes(a), Encoding.UTF8.GetBytes(b));
}
