using ZB.MOM.WW.Secrets.Abstractions;

namespace ZB.MOM.WW.Secrets.MasterKey;

/// <summary>
/// Resolves the master key (KEK) from a base64-encoded environment variable named by
/// <see cref="MasterKeyOptions.EnvVarName"/>. The variable is read fresh on every call so a rotated
/// value takes effect immediately.
/// </summary>
public sealed class EnvironmentMasterKeyProvider : MasterKeyProviderBase
{
    /// <summary>Creates the provider bound to <paramref name="options"/>.</summary>
    /// <param name="options">The master-key configuration (uses <see cref="MasterKeyOptions.EnvVarName"/>).</param>
    public EnvironmentMasterKeyProvider(MasterKeyOptions options) : base(options)
    {
    }

    /// <inheritdoc />
    protected override byte[] ResolveKeyBytes()
    {
        string envVarName = Options.EnvVarName;
        string? value = Environment.GetEnvironmentVariable(envVarName);
        if (string.IsNullOrEmpty(value))
        {
            throw new MasterKeyUnavailableException(
                $"Master key environment variable '{envVarName}' is not set or is empty.");
        }

        try
        {
            return Convert.FromBase64String(value.Trim());
        }
        catch (FormatException ex)
        {
            throw new MasterKeyUnavailableException(
                $"Master key environment variable '{envVarName}' is not valid base64: {ex.Message}");
        }
    }
}
