namespace Infrastructure.Auth;

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

/// <summary>
/// 授权信息模型
/// </summary>
public class LicenseInfo
{
    /// <summary>
    /// 授权用户
    /// </summary>
    public string UserName { get; set; }

    /// <summary>
    /// 授权开始时间
    /// </summary>
    public DateTime StartTime { get; set; }

    /// <summary>
    /// 授权结束时间（永久授权可设为DateTime.MaxValue）
    /// </summary>
    public DateTime EndTime { get; set; }

    /// <summary>
    /// 授权类型（试用/正式/永久）
    /// </summary>
    public LicenseType LicenseType { get; set; }

    /// <summary>
    /// 硬件绑定信息（可选，用于防止多设备使用）
    /// </summary>
    public string HardwareId { get; set; }
}

/// <summary>
/// 授权类型
/// </summary>
public enum LicenseType
{
    Trial, // 试用授权
    Subscription, // 订阅授权
    Permanent // 永久授权
}

/// <summary>
/// 授权管理核心类
/// </summary>
public class LicenseManager
{
    // 加密密钥（实际使用中建议替换为自己的密钥，长度需为16/24/32字节）
    private readonly byte[] _key = Convert.FromBase64String("0TXis2sTDEnNAAe/6bYqG7xwapKQcXUlI+WwrMlKv5I=");
    private readonly byte[] _iv = Convert.FromBase64String("UdDHCIRoqIn4shpJCGRUpg==");

    /// <summary>
    /// 生成授权文件
    /// </summary>
    /// <param name="info">授权信息</param>
    /// <returns>加密后的授权字符串（可保存为文件）</returns>
    public string GenerateLicense(LicenseInfo info)
    {
        // 序列化授权信息
        string json = JsonSerializer.Serialize(info);

        // 加密
        return EncryptString(json);
    }

    /// <summary>
    /// 验证授权有效性
    /// </summary>
    /// <param name="licenseString">加密的授权字符串</param>
    /// <param name="errorMsg">验证失败时的错误信息</param>
    /// <returns>是否有效</returns>
    public bool ValidateLicense(string licenseString, out string errorMsg)
    {
        errorMsg = string.Empty;
        try
        {
            // 解密授权信息
            string json = DecryptString(licenseString);
            var license = JsonSerializer.Deserialize<LicenseInfo>(json);

            // 1. 检查硬件绑定（可选）
            if (!string.IsNullOrEmpty(license.HardwareId) &&
                license.HardwareId != GetHardwareId())
            {
                errorMsg = "授权与当前设备不匹配";
                return false;
            }

            // 2. 检查时间有效性
            DateTime now = DateTime.Now;
            if (now < license.StartTime)
            {
                errorMsg = $"授权未生效，生效时间：{license.StartTime:yyyy-MM-dd}";
                return false;
            }

            // 永久授权跳过结束时间检查
            if (license.LicenseType != LicenseType.Permanent && now > license.EndTime)
            {
                errorMsg = $"授权已过期，过期时间：{license.EndTime:yyyy-MM-dd}";
                return false;
            }

            return true;
        }
        catch (Exception ex)
        {
            errorMsg = $"授权验证失败：{ex.Message}";
            return false;
        }
    }

    /// <summary>
    /// 获取授权剩余时间
    /// </summary>
    /// <param name="licenseString">加密的授权字符串</param>
    /// <returns>剩余时间（永久授权返回null）</returns>
    public TimeSpan? GetRemainingTime(string licenseString)
    {
        try
        {
            string json = DecryptString(licenseString);
            var license = JsonSerializer.Deserialize<LicenseInfo>(json);

            if (license.LicenseType == LicenseType.Permanent)
                return null; // 永久授权无剩余时间

            DateTime now = DateTime.Now;
            if (now > license.EndTime)
                return TimeSpan.Zero; // 已过期

            return license.EndTime - now;
        }
        catch
        {
            return TimeSpan.Zero;
        }
    }

    /// <summary>
    /// 加密字符串
    /// </summary>
    private string EncryptString(string plainText)
    {
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = _key;
            aesAlg.IV = _iv;
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
            byte[] encrypted = encryptor.TransformFinalBlock(Encoding.UTF8.GetBytes(plainText), 0, plainText.Length);
            return Convert.ToBase64String(encrypted);
        }
    }

    /// <summary>
    /// 解密字符串
    /// </summary>
    private string DecryptString(string cipherText)
    {
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = _key;
            aesAlg.IV = _iv;

            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            byte[] decrypted = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
            return Encoding.UTF8.GetString(decrypted);
        }
    }

    /// <summary>
    /// 获取硬件唯一标识（简化版，实际可增强）
    /// </summary>
    public string GetHardwareId()
    {
        // 实际应用中可结合CPU、硬盘、网卡等信息生成唯一ID
        // 这里仅作为示例
        return Environment.MachineName;
    }
}