using System.Security.Cryptography;

namespace SIGCM2.Infrastructure.Security;

public static class RsaKeyLoader
{
    /// <summary>
    /// Loads the RSA private key from environment variable (production)
    /// or from the PEM file on disk (development).
    /// </summary>
    public static RSA LoadPrivateKey(JwtOptions options)
    {
        var pem = options.PrivateKey ?? ReadPemFile(options.PrivateKeyPath, "private.pem");
        var rsa = RSA.Create();
        rsa.ImportFromPem(pem);
        return rsa;
    }

    /// <summary>
    /// Loads the RSA public key from environment variable (production)
    /// or from the PEM file on disk (development).
    /// </summary>
    public static RSA LoadPublicKey(JwtOptions options)
    {
        var pem = options.PublicKey ?? ReadPemFile(options.PublicKeyPath, "public.pem");
        var rsa = RSA.Create();
        rsa.ImportFromPem(pem);
        return rsa;
    }

    private static string ReadPemFile(string? path, string fallbackName)
    {
        if (string.IsNullOrWhiteSpace(path))
        {
            throw new InvalidOperationException(
                $"JWT key not configured. Set the env var or provide a path for {fallbackName}. " +
                $"Run: pwsh -File scripts/generate-keys.ps1");
        }

        if (!File.Exists(path))
        {
            throw new FileNotFoundException(
                $"JWT key file not found at '{path}'. " +
                $"Run: pwsh -File scripts/generate-keys.ps1", path);
        }

        return File.ReadAllText(path);
    }
}
