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

namespace NcProgramManager.Licensing
{
    internal class LicenseValidator : ILicenseValidator
    {
        // Real vendor public key -- generated 2026-05-17 with LicenseGenerator keygen.
        private const string PublicKeyXml = "<RSAKeyValue><Modulus>jym+FWWeMb4g2ijaPlMn427s36sdv0FkDp5mKX+wMYGgRSIwUoDnG6nVCj6Z9k25uDf7714BXbg0IaJ/C8KE5TMgqgqsWA9hT79CdJR1eADM5jwMCo43mIIMuDplzdlmgfaW/JwE7QsxzdpfpW1uxU5DVJzsV/RZaRabTK2nSsvzHclMvB+jIQ9VobwTAyYhrvF7nYLtSdGl4YvvZ1O2fzJudvrlCrl5nnRqfPZC+0YnEwcLW0BzWxMiH0UGR/Gz4h7L05OkEwiXYtO+vkslkxIA6jraU0qjoFfDCaZ6HajWZ8lphCpw00Nwa8nEvaiuCRqN/lVOm/9kHXFuAXtA/Q==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

        private readonly string _publicKeyXml;

        // Uses embedded vendor public key.
        internal LicenseValidator() : this(PublicKeyXml) { }

        // Accepts any public key XML — used in unit tests.
        internal LicenseValidator(string publicKeyXml)
        {
            _publicKeyXml = publicKeyXml;
        }

        public bool Validate(string fingerprint, string licenseBase64)
        {
            try
            {
                byte[] signature = Convert.FromBase64String(licenseBase64);
                byte[] data = Encoding.UTF8.GetBytes(fingerprint);
                using (var rsa = new RSACryptoServiceProvider())
                {
                    rsa.FromXmlString(_publicKeyXml);
                    using (var sha256 = new SHA256CryptoServiceProvider())
                    {
                        return rsa.VerifyData(data, sha256, signature);
                    }
                }
            }
            catch
            {
                return false;
            }
        }
    }
}
