using System.Text;
using ZB.MOM.WW.Secrets.Abstractions;
using ZB.MOM.WW.Secrets.Crypto;
using ZB.MOM.WW.Secrets.Tests.Fakes;

namespace ZB.MOM.WW.Secrets.Tests.Crypto;

public class AesGcmEnvelopeCipherTests
{
    [Fact]
    public void RoundTrips()
    {
        var provider = new FakeMasterKeyProvider("k1");
        var cipher = new AesGcmEnvelopeCipher(provider);
        var name = new SecretName("sql/foo");

        StoredSecret row = cipher.Encrypt(name, "hunter2", SecretContentType.Text);

        Assert.Equal("k1", row.KekId);
        // Ciphertext must not leak the plaintext in the clear.
        byte[] plaintextBytes = Encoding.UTF8.GetBytes("hunter2");
        Assert.False(Contains(row.Ciphertext, plaintextBytes));

        string decrypted = cipher.Decrypt(row);
        Assert.Equal("hunter2", decrypted);
    }

    [Fact]
    public void TwoEncryptsProduceDifferentNonces()
    {
        var provider = new FakeMasterKeyProvider("k1");
        var cipher = new AesGcmEnvelopeCipher(provider);
        var name = new SecretName("sql/foo");

        // Same plaintext + name encrypted twice must yield a fresh nonce (and therefore a distinct
        // ciphertext) each time — the AES-GCM (key, nonce) uniqueness invariant.
        StoredSecret first = cipher.Encrypt(name, "hunter2", SecretContentType.Text);
        StoredSecret second = cipher.Encrypt(name, "hunter2", SecretContentType.Text);

        Assert.False(first.Nonce.AsSpan().SequenceEqual(second.Nonce));
        Assert.False(first.Ciphertext.AsSpan().SequenceEqual(second.Ciphertext));
    }

    [Fact]
    public void TamperedCiphertextThrows()
    {
        var provider = new FakeMasterKeyProvider("k1");
        var cipher = new AesGcmEnvelopeCipher(provider);
        var name = new SecretName("sql/foo");

        StoredSecret row = cipher.Encrypt(name, "hunter2", SecretContentType.Text);
        row.Ciphertext[0] ^= 0xFF;

        Assert.Throws<SecretDecryptionException>(() => cipher.Decrypt(row));
    }

    [Fact]
    public void AadBindingRejectsRenamedRow()
    {
        var provider = new FakeMasterKeyProvider("k1");
        var cipher = new AesGcmEnvelopeCipher(provider);

        StoredSecret row = cipher.Encrypt(new SecretName("sql/foo"), "hunter2", SecretContentType.Text);
        var renamed = row with { Name = new SecretName("sql/bar") };

        Assert.Throws<SecretDecryptionException>(() => cipher.Decrypt(renamed));
    }

    [Fact]
    public void WrongKekThrows()
    {
        // Both providers report KekId "k1" but hold different random key bytes.
        var providerA = new FakeMasterKeyProvider("k1");
        var providerB = new FakeMasterKeyProvider("k1");
        var cipherA = new AesGcmEnvelopeCipher(providerA);
        var cipherB = new AesGcmEnvelopeCipher(providerB);

        StoredSecret row = cipherA.Encrypt(new SecretName("sql/foo"), "hunter2", SecretContentType.Text);

        // Matching KekId string but wrong key material must still fail closed (unwrap tag mismatch).
        Assert.Throws<SecretDecryptionException>(() => cipherB.Decrypt(row));
    }

    [Fact]
    public void UnknownKekIdThrows()
    {
        var providerK1 = new FakeMasterKeyProvider("k1");
        var providerK2 = new FakeMasterKeyProvider("k2");
        var cipherK1 = new AesGcmEnvelopeCipher(providerK1);
        var cipherK2 = new AesGcmEnvelopeCipher(providerK2);

        StoredSecret row = cipherK1.Encrypt(new SecretName("sql/foo"), "hunter2", SecretContentType.Text);

        var ex = Assert.Throws<SecretDecryptionException>(() => cipherK2.Decrypt(row));
        Assert.Contains("unknown KEK", ex.Message, StringComparison.Ordinal);
    }

    [Fact]
    public void Rewrap_RewrapsDek_BodyStillDecryptsUnderNewKek()
    {
        var oldKek = new FakeMasterKeyProvider("kek-old");
        var newKek = new FakeMasterKeyProvider("kek-new");
        var oldCipher = new AesGcmEnvelopeCipher(oldKek);
        var name = new SecretName("sql/foo");

        StoredSecret row = oldCipher.Encrypt(name, "hunter2", SecretContentType.Text);
        Assert.Equal("kek-old", row.KekId);

        // Rewrap is provider-explicit — it can be driven through any cipher instance.
        StoredSecret rewrapped = oldCipher.Rewrap(row, oldKek, newKek);

        Assert.Equal("kek-new", rewrapped.KekId);
        // The DEK-sealed body is untouched; only the KEK-wrap envelope changed.
        Assert.True(rewrapped.Ciphertext.AsSpan().SequenceEqual(row.Ciphertext));
        Assert.True(rewrapped.Nonce.AsSpan().SequenceEqual(row.Nonce));
        Assert.True(rewrapped.Tag.AsSpan().SequenceEqual(row.Tag));
        Assert.False(rewrapped.WrappedDek.AsSpan().SequenceEqual(row.WrappedDek));

        // The rewrapped row decrypts under the NEW KEK...
        var newCipher = new AesGcmEnvelopeCipher(newKek);
        Assert.Equal("hunter2", newCipher.Decrypt(rewrapped));
        // ...and no longer under the OLD KEK (kek_id now names the new KEK; old cipher fails closed).
        Assert.Throws<SecretDecryptionException>(() => oldCipher.Decrypt(rewrapped));
    }

    [Fact]
    public void Rewrap_PreservesRevisionTimestampsTombstoneAndMetadata()
    {
        var oldKek = new FakeMasterKeyProvider("kek-old");
        var newKek = new FakeMasterKeyProvider("kek-new");
        var cipher = new AesGcmEnvelopeCipher(oldKek);

        StoredSecret row = cipher.Encrypt(new SecretName("sql/foo"), "hunter2", SecretContentType.Text) with
        {
            Revision = 7,
            IsDeleted = true,
            DeletedUtc = DateTimeOffset.UnixEpoch,
            CreatedUtc = DateTimeOffset.UnixEpoch,
            UpdatedUtc = DateTimeOffset.UnixEpoch.AddMinutes(5),
            CreatedBy = "alice",
            UpdatedBy = "bob",
            Description = "the foo password",
        };

        StoredSecret rewrapped = cipher.Rewrap(row, oldKek, newKek);

        // Only the wrap envelope + kek_id change — a rewrap must be invisible to (updated_utc, revision) LWW.
        Assert.Equal(7, rewrapped.Revision);
        Assert.True(rewrapped.IsDeleted);
        Assert.Equal(row.DeletedUtc, rewrapped.DeletedUtc);
        Assert.Equal(row.CreatedUtc, rewrapped.CreatedUtc);
        Assert.Equal(row.UpdatedUtc, rewrapped.UpdatedUtc);
        Assert.Equal("alice", rewrapped.CreatedBy);
        Assert.Equal("bob", rewrapped.UpdatedBy);
        Assert.Equal("the foo password", rewrapped.Description);
        Assert.Equal(SecretContentType.Text, rewrapped.ContentType);
    }

    [Fact]
    public void Rewrap_WrongOldKekId_FailsClosed()
    {
        var actualKek = new FakeMasterKeyProvider("kek-old");
        var wrongOld = new FakeMasterKeyProvider("kek-somethingelse");
        var newKek = new FakeMasterKeyProvider("kek-new");
        var cipher = new AesGcmEnvelopeCipher(actualKek);

        StoredSecret row = cipher.Encrypt(new SecretName("sql/foo"), "hunter2", SecretContentType.Text);

        // Row is wrapped by "kek-old" but the caller claims the old KEK is "kek-somethingelse".
        var ex = Assert.Throws<SecretDecryptionException>(() => cipher.Rewrap(row, wrongOld, newKek));
        Assert.Contains("kek-old", ex.Message, StringComparison.Ordinal);
    }

    [Fact]
    public void Rewrap_CorrectKekIdButWrongKeyMaterial_FailsClosed()
    {
        // Same KEK-id string, different key bytes → the unwrap must fail closed (tag mismatch),
        // never emitting a garbage DEK.
        var realOld = new FakeMasterKeyProvider("kek-old");
        var imposterOld = new FakeMasterKeyProvider("kek-old"); // same id, fresh random bytes
        var newKek = new FakeMasterKeyProvider("kek-new");
        var cipher = new AesGcmEnvelopeCipher(realOld);

        StoredSecret row = cipher.Encrypt(new SecretName("sql/foo"), "hunter2", SecretContentType.Text);

        Assert.Throws<SecretDecryptionException>(() => cipher.Rewrap(row, imposterOld, newKek));
    }

    private static bool Contains(byte[] haystack, byte[] needle)
    {
        if (needle.Length == 0 || haystack.Length < needle.Length)
        {
            return false;
        }

        for (int i = 0; i <= haystack.Length - needle.Length; i++)
        {
            bool match = true;
            for (int j = 0; j < needle.Length; j++)
            {
                if (haystack[i + j] != needle[j])
                {
                    match = false;
                    break;
                }
            }

            if (match)
            {
                return true;
            }
        }

        return false;
    }
}
