using System.Security.Cryptography;
using System.Text;
using Baya.Application.Contracts.Common;

namespace Baya.Tests.Setup.Setups;

/// <summary>
/// Deterministic-key <see cref="IFieldEncryptor"/> for tests: reversible base64 "encryption" plus an
/// HMAC lookup hash. Exposed as a single shared instance because EF caches the model (and therefore
/// the value converters built from the encryptor) — every test context must use the same instance,
/// mirroring the production singleton registration.
/// </summary>
public sealed class TestFieldEncryptor : IFieldEncryptor
{
    public static readonly TestFieldEncryptor Instance = new();

    private static readonly byte[] HashKey = "test-field-hash-key"u8.ToArray();

    private TestFieldEncryptor()
    {
    }

    public string Encrypt(string plaintext) =>
        string.IsNullOrEmpty(plaintext) ? plaintext : Convert.ToBase64String(Encoding.UTF8.GetBytes(plaintext));

    public string Decrypt(string ciphertext) =>
        string.IsNullOrEmpty(ciphertext) ? ciphertext : Encoding.UTF8.GetString(Convert.FromBase64String(ciphertext));

    public string Hash(string value)
    {
        if (string.IsNullOrEmpty(value))
            return value;

        using var hmac = new HMACSHA256(HashKey);
        return Convert.ToHexString(hmac.ComputeHash(Encoding.UTF8.GetBytes(value)));
    }
}