using System.Text;
using ZB.MOM.WW.Secrets.Abstractions;

namespace ZB.MOM.WW.Secrets.Ui.Tests.Fakes;

/// <summary>
/// A trivial, reversible <see cref="ISecretCipher"/> stand-in for UI tests. It does not perform real
/// cryptography — it simply carries the UTF-8 plaintext in <see cref="StoredSecret.Ciphertext"/> so a
/// test can prove the editor's encrypt→upsert round-trips back to the entered value. Never used in
/// production. A <see cref="FailDecrypt"/> flag lets a test drive the decrypt-failure reveal path.
/// </summary>
public sealed class FakeCipher : ISecretCipher
{
    /// <summary>When <c>true</c>, <see cref="Decrypt"/> throws to exercise the failure path.</summary>
    public bool FailDecrypt { get; set; }

    /// <inheritdoc />
    public StoredSecret Encrypt(SecretName name, string plaintext, SecretContentType contentType)
        => new()
        {
            Name = name,
            ContentType = contentType,
            Ciphertext = Encoding.UTF8.GetBytes(plaintext),
            Nonce = [1, 2, 3],
            Tag = [4, 5, 6],
            WrappedDek = [7, 8, 9],
            WrapNonce = [10, 11, 12],
            WrapTag = [13, 14, 15],
            KekId = "fake-kek",
            Revision = 0,
            CreatedUtc = default,
            UpdatedUtc = default,
        };

    /// <inheritdoc />
    public string Decrypt(StoredSecret secret)
    {
        if (FailDecrypt)
        {
            throw new SecretDecryptionException("Fake decrypt failure.");
        }

        return Encoding.UTF8.GetString(secret.Ciphertext);
    }

    /// <inheritdoc />
    public StoredSecret Rewrap(StoredSecret secret, IMasterKeyProvider oldKek, IMasterKeyProvider newKek)
        => secret with { KekId = newKek.KekId };
}
