using Microsoft.AspNetCore.Mvc;
using OtpNet;
using System.Text;
using XSystem.Security.Cryptography;

namespace AUTS_Server.Service
{
    public class EncryptionService : IEncryptionService
    {
        public string BuildTotpUri(string secret, string user, string issuer)
        {
            var issuerParameter = string.IsNullOrEmpty(issuer) ? "" : $"&issuer={Uri.EscapeDataString(issuer)}";
            return $"otpauth://totp/{Uri.EscapeDataString(user)}?secret={secret}{issuerParameter}&algorithm=SHA1&digits=6&period=30";
        }

        public string Encrypt(string str)
        {
            MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider();
            byte[] array = md5CryptoServiceProvider.ComputeHash(Encoding.Default.GetBytes(str));
            StringBuilder stringBuilder = new StringBuilder();
            foreach (byte b in array)
            {
                stringBuilder.Append(b.ToString("x2"));
            }
            return stringBuilder.ToString().ToUpper();
        }

        public GenerateKeyinfo GenerateKey()
        {
            GenerateKeyinfo generateKeyinfo = new GenerateKeyinfo();
            var key = KeyGeneration.GenerateRandomKey(20);
            string base32Secret = Base32Encoding.ToString(key);
            var issuer = "AUTS";
            var userAccount = "new.uts-data.com";
            string totpSetupUrl = BuildTotpUri(base32Secret, userAccount, issuer);
            generateKeyinfo.SecretKey = base32Secret;
            generateKeyinfo.QrCodeSetupUrl = totpSetupUrl;
            return generateKeyinfo;
            // 返回密钥和二维码URL
            //return Ok(new { SecretKey = base32Secret, QrCodeSetupUrl = totpSetupUrl });
        }

        public bool VerifyTOTP(VerifyTOTPRequest request)
        {
            var key = Base32Encoding.ToBytes(request.SecretKey);
            long timeStepMatched;
            var totp = new Totp(key);
            var TotpCode = "";
            bool isValid = totp.VerifyTotp(TotpCode, out timeStepMatched, new VerificationWindow(2, 2));

            if (isValid)
            {
                // 验证成功
                return true;
            }
            else
            {
                // 验证失;
                return false;
            }
        }
    }
    public class GenerateKeyinfo
    {
        public string SecretKey { get; set; }
        public string QrCodeSetupUrl { get; set; }
    }
}
