using System.Security.Cryptography;
using DodoSSH.Client.Domain;
using DodoSSH.Contracts;
using DodoSSH.Crypto;

namespace DodoSSH.Client.Sync;

/// <summary>
/// Turns a tag into an item payload and back.
/// </summary>
/// <remarks>
/// <para>
/// Mirrors <see cref="HostGroupCipher"/> exactly, including the rule that a payload is sealed at the version
/// the server <em>will</em> assign rather than the one it replaces — see <see cref="SyncVersions"/>.
/// </para>
/// <para>
/// <b>The resource type is the one thing not to copy, and this type is where copying it is most tempting.</b>
/// <c>SyncEntityType.Tag</c> is 5 and <c>CryptoSpec.AadResourceType.Tag</c> is 8, because the crypto enum
/// carries None, User, Device and Vault ahead of the item types. A cast from one to the other compiles, and
/// 5 in the crypto enum is <c>Credential</c> — so every tag in the vault would be sealed under the resource
/// type for a password. It would encrypt perfectly and decrypt perfectly on the machine that wrote it, and
/// the first thing to notice would be another implementation refusing the item. The AAD is frozen into
/// stored ciphertext, so by then it is not a bug that can be fixed by a release.
/// </para>
/// </remarks>
public static class TagCipher
{
    private const CryptoSpec.AadResourceType Resource = CryptoSpec.AadResourceType.Tag;

    /// <summary>Encrypts a tag.</summary>
    /// <param name="tag">The tag. Must be valid for storage.</param>
    /// <param name="vaultKey">The vault key, which the data key is wrapped under.</param>
    /// <param name="entityId">The item id, which the AAD binds.</param>
    /// <param name="keyGeneration">The vault's current key generation.</param>
    /// <param name="itemVersion">The version this payload will hold once the server accepts it.</param>
    public static EncryptedPayload Seal(
        TagSecret tag,
        ReadOnlySpan<byte> vaultKey,
        Guid entityId,
        uint keyGeneration,
        int itemVersion)
    {
        ArgumentNullException.ThrowIfNull(tag);
        ArgumentOutOfRangeException.ThrowIfLessThan(itemVersion, 1);

        var plaintext = TagSecretCodec.Encode(tag);
        var dataKey = ItemKeys.CreateDataKey();

        try
        {
            var dataKeyId = Guid.CreateVersion7();

            var wrappedDataKey = ItemKeys.WrapDataKey(
                dataKey, vaultKey, Resource, entityId, keyGeneration, (uint)itemVersion);

            var envelope = ItemKeys.SealPayload(
                dataKey, plaintext, Resource, entityId, dataKeyId, keyGeneration, (uint)itemVersion);

            return new EncryptedPayload(
                envelope, wrappedDataKey, dataKeyId, keyGeneration, CryptoSpec.CurrentAadVersion);
        }
        finally
        {
            CryptographicOperations.ZeroMemory(dataKey);

            // Wiped like every other payload in this folder, and here for the smallest reason of all: the
            // buffer holds one word somebody chose for a filter. It is wiped anyway, because the rule this
            // folder follows is that plaintext does not outlive the call that made it, and an exception for
            // the case that seems harmless is how the rule stops being one.
            CryptographicOperations.ZeroMemory(plaintext);
        }
    }

    /// <summary>Decrypts a tag.</summary>
    /// <inheritdoc cref="HostCipher.TryOpen" path="/returns" />
    public static TagSecretDocument? TryOpen(
        EncryptedPayload payload,
        ReadOnlySpan<byte> vaultKey,
        Guid entityId,
        int itemVersion)
    {
        ArgumentNullException.ThrowIfNull(payload);

        if (itemVersion < 1 || payload.WrappedDataKey.Length == 0)
        {
            return null;
        }

        var dataKey = ItemKeys.TryUnwrapDataKey(
            vaultKey,
            payload.WrappedDataKey,
            Resource,
            entityId,
            payload.KeyGeneration,
            (uint)itemVersion);

        if (dataKey is null)
        {
            return null;
        }

        try
        {
            var plaintext = ItemKeys.TryOpenPayload(
                dataKey,
                payload.Envelope,
                Resource,
                entityId,
                payload.DataKeyId,
                payload.KeyGeneration,
                (uint)itemVersion);

            if (plaintext is null)
            {
                return null;
            }

            try
            {
                return TagSecretCodec.TryDecode(plaintext, out var document) ? document : null;
            }
            finally
            {
                CryptographicOperations.ZeroMemory(plaintext);
            }
        }
        finally
        {
            CryptographicOperations.ZeroMemory(dataKey);
        }
    }
}
