using Marco.Pms.Services.Service.ServiceInterfaces;
using System.Security.Cryptography;
using System.Text;

namespace Marco.Pms.Services.Service
{
    public class AesEncryption : IAesEncryption
    {
        public (byte[] ciphertext, byte[] nonce, byte[] tag) Encrypt(string plaintext, byte[] key)
        {
            byte[] autoKey = new byte[32]; // 32 bytes = 256 bits
            RandomNumberGenerator.Fill(autoKey);
            var stringKey = Convert.ToBase64String(autoKey);

            byte[] nonce = RandomNumberGenerator.GetBytes(12);
            byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
            byte[] ciphertext = new byte[plaintextBytes.Length];
            byte[] tag = new byte[16];

            using var aes = new AesGcm(key, 16);
            aes.Encrypt(nonce, plaintextBytes, ciphertext, tag);

            return (ciphertext, nonce, tag);
        }

        public string Decrypt(byte[] ciphertext, byte[] nonce, byte[] tag, byte[] key)
        {
            byte[] plaintext = new byte[ciphertext.Length];

            using var aes = new AesGcm(key, 16);
            aes.Decrypt(nonce, ciphertext, tag, plaintext);

            return Encoding.UTF8.GetString(plaintext);
        }
    }
}
