using Newtonsoft.Json;
using System;
using System.IO;
using System.Security.Cryptography;

namespace SWRIS.Extensions
{
    public static class JsonCryptoHelper
    {
        public static void EncryptToFile<T>(T data, string filePath, string key, string iv)
        {
            // 序列化为 JSON 字符串
            string json = JsonConvert.SerializeObject(data, Formatting.None);

            // 加密 JSON 字符串
            byte[] encrypted = EncryptStringToBytes(json, key, iv);

            // 写入文件
            File.WriteAllBytes(filePath, encrypted);
        }

        public static T DecryptFromFile<T>(string filePath, string key, string iv)
        {
            // 读取加密文件
            byte[] encrypted = File.ReadAllBytes(filePath);

            // 解密字节数组
            string json = DecryptStringFromBytes(encrypted, key, iv);

            // 反序列化为对象
            return JsonConvert.DeserializeObject<T>(json);
        }

        private static byte[] EncryptStringToBytes(string plainText, string key, string iv)
        {
            byte[] keyBytes = Convert.FromBase64String(key);
            byte[] ivBytes = Convert.FromBase64String(iv);
            byte[] encrypted;

            using (Aes aes = Aes.Create())
            {
                aes.Key = keyBytes;
                aes.IV = ivBytes;

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(cs))
                        {
                            sw.Write(plainText);
                        }
                        encrypted = ms.ToArray();
                    }
                }
            }

            return encrypted;
        }

        private static string DecryptStringFromBytes(byte[] cipherText, string key, string iv)
        {
            byte[] keyBytes = Convert.FromBase64String(key);
            byte[] ivBytes = Convert.FromBase64String(iv);
            string plaintext;

            using (Aes aes = Aes.Create())
            {
                aes.Key = keyBytes;
                aes.IV = ivBytes;

                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                using (MemoryStream ms = new MemoryStream(cipherText))
                {
                    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader sr = new StreamReader(cs))
                        {
                            plaintext = sr.ReadToEnd();
                        }
                    }
                }
            }

            return plaintext;
        }
    }
}