// Copyright (C) 2021-present sam (starshines.gay)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

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

namespace Catalogger.Backend.Database;

public class EncryptionService(Config config) : IEncryptionService
{
    private readonly byte[] _secretKey = Convert.FromBase64String(config.Database.EncryptionKey);

    public byte[] Encrypt(string data)
    {
        using var aes = Aes.Create();
        aes.Key = _secretKey;

        var output = new List<byte>();
        output.AddRange(aes.IV);

        var plaintext = Encoding.UTF8.GetBytes(data);
        var ciphertext = aes.EncryptCbc(plaintext, aes.IV);

        output.AddRange(ciphertext);
        return output.ToArray();
    }

    public string Decrypt(byte[] input)
    {
        using var aes = Aes.Create();
        aes.Key = _secretKey;

        var iv = input.Take(aes.IV.Length).ToArray();
        var ciphertext = input.Skip(aes.IV.Length).ToArray();
        var plaintext = aes.DecryptCbc(ciphertext, iv);

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