using System.Collections.Concurrent;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.Secrets.Abstractions;

namespace ZB.MOM.WW.Secrets;

/// <summary>
/// The default <see cref="ISecretResolver"/>: loads an encrypted row from the store, decrypts it
/// on demand, and serves it from a short-lived in-memory cache. Every resolution — hit, miss,
/// tombstone, or decryption failure — emits an <see cref="AuditEvent"/> recording <b>which</b>
/// secret was accessed and the outcome. The plaintext value is <b>never</b> placed in any audit
/// field.
/// </summary>
/// <remarks>
/// <para>
/// <b>Security note — the cache holds decrypted secret material in process memory.</b> The TTL is
/// deliberately kept short (configured by the caller / DI) so plaintext lives only briefly and a
/// rotation or revocation is picked up quickly. <see cref="Invalidate"/> lets the write path evict
/// an entry immediately after a rotate or delete. The cache is keyed by the normalized
/// <see cref="SecretName.Value"/> and is safe for concurrent use.
/// </para>
/// <para>
/// A missing or tombstoned secret is <b>not</b> an exception: <see cref="GetAsync"/> returns
/// <c>null</c> and audits a <see cref="AuditOutcome.Failure"/> with a <c>not-found</c> action, so a
/// consumer can distinguish "absent" from "present" without a throw on the hot path.
/// </para>
/// <para>
/// A <b>decryption or integrity failure</b> (tampered ciphertext or the wrong KEK) is different: it
/// is <b>fail-loud</b>. <see cref="GetAsync"/> audits a <see cref="AuditOutcome.Failure"/> with a
/// <c>decryption-failed</c> action and then rethrows the <see cref="SecretDecryptionException"/> — it
/// is never masked as a benign miss or a <c>null</c>. The audit records only the secret name; the
/// ciphertext and any value are never included.
/// </para>
/// </remarks>
public sealed class DefaultSecretResolver : ISecretResolver, ISecretCacheInvalidator
{
    private const string SystemActor = "system";
    private const string AuditCategory = "Secrets";
    private const string ResolveAction = "secret.resolve";
    private const string NotFoundAction = "secret.resolve.not-found";
    private const string DecryptionFailedAction = "secret.resolve.decryption-failed";

    private readonly ISecretStore _store;
    private readonly ISecretCipher _cipher;
    private readonly IAuditWriter _audit;
    private readonly TimeSpan _cacheTtl;
    private readonly ISecretActorAccessor? _actorAccessor;
    private readonly TimeProvider _timeProvider;

    // Keyed by SecretName.Value. Holds DECRYPTED plaintext — kept only for the short TTL.
    private readonly ConcurrentDictionary<string, CacheEntry> _cache = new(StringComparer.Ordinal);

    /// <summary>
    /// Creates a resolver over the given store, cipher, and audit writer.
    /// </summary>
    /// <param name="store">The encrypted-row store to read from.</param>
    /// <param name="cipher">The cipher used to decrypt a loaded row.</param>
    /// <param name="audit">The audit sink; one event is written per resolve (never the value).</param>
    /// <param name="cacheTtl">
    /// How long a decrypted value is cached in memory. Keep this short — it is plaintext secret
    /// material. A non-positive value effectively disables caching (every entry is already expired).
    /// </param>
    /// <param name="actorAccessor">
    /// Optional accessor for the current principal to attribute the audit to; a <c>null</c> accessor
    /// (or a <c>null</c> <see cref="ISecretActorAccessor.CurrentActor"/>) is recorded as
    /// <c>"system"</c>.
    /// </param>
    /// <param name="timeProvider">The clock (defaults to <see cref="TimeProvider.System"/>).</param>
    public DefaultSecretResolver(
        ISecretStore store,
        ISecretCipher cipher,
        IAuditWriter audit,
        TimeSpan cacheTtl,
        ISecretActorAccessor? actorAccessor = null,
        TimeProvider? timeProvider = null)
    {
        _store = store ?? throw new ArgumentNullException(nameof(store));
        _cipher = cipher ?? throw new ArgumentNullException(nameof(cipher));
        _audit = audit ?? throw new ArgumentNullException(nameof(audit));
        _cacheTtl = cacheTtl;
        _actorAccessor = actorAccessor;
        _timeProvider = timeProvider ?? TimeProvider.System;
    }

    /// <inheritdoc />
    public async Task<string?> GetAsync(SecretName name, CancellationToken ct)
    {
        string key = name.Value;
        DateTimeOffset now = _timeProvider.GetUtcNow();

        // 1) Serve from cache while the entry is still live.
        if (_cache.TryGetValue(key, out CacheEntry cached) && now < cached.ExpiresUtc)
        {
            await AuditSuccessAsync(name, source: "cache", ct).ConfigureAwait(false);
            return cached.Plaintext;
        }

        // 2) Load the encrypted row.
        StoredSecret? row = await _store.GetAsync(name, ct).ConfigureAwait(false);
        if (row is null || row.IsDeleted)
        {
            await AuditNotFoundAsync(name, ct).ConfigureAwait(false);
            return null;
        }

        // Decrypt on demand and cache the plaintext for the short TTL. A decryption/integrity
        // failure (tampered ciphertext or wrong KEK) MUST leave an audit trail and then propagate —
        // it is never masked as a benign miss. The audit records only the name; never the value.
        string plaintext;
        try
        {
            plaintext = _cipher.Decrypt(row);
        }
        catch (SecretDecryptionException)
        {
            await AuditDecryptionFailedAsync(name, ct).ConfigureAwait(false);
            throw;
        }

        _cache[key] = new CacheEntry(plaintext, now + _cacheTtl, row.Revision);

        await AuditSuccessAsync(name, source: "store", ct).ConfigureAwait(false);
        return plaintext;
    }

    /// <summary>
    /// Evicts the cached plaintext for <paramref name="name"/>, if any. The admin / write path
    /// calls this (via <see cref="ISecretCacheInvalidator"/>) immediately after a rotate or delete
    /// so a stale value is not served for the remainder of its TTL. Cheap and idempotent.
    /// </summary>
    /// <param name="name">The secret whose cache entry to remove.</param>
    public void Invalidate(SecretName name) => _cache.TryRemove(name.Value, out _);

    private Task AuditSuccessAsync(SecretName name, string source, CancellationToken ct) =>
        WriteAuditAsync(name, ResolveAction, AuditOutcome.Success, $"{{\"source\":\"{source}\"}}", ct);

    private Task AuditNotFoundAsync(SecretName name, CancellationToken ct) =>
        WriteAuditAsync(name, NotFoundAction, AuditOutcome.Failure, "{\"reason\":\"not-found\"}", ct);

    private Task AuditDecryptionFailedAsync(SecretName name, CancellationToken ct) =>
        WriteAuditAsync(
            name, DecryptionFailedAction, AuditOutcome.Failure, "{\"reason\":\"decryption-failed\"}", ct);

    private Task WriteAuditAsync(
        SecretName name, string action, AuditOutcome outcome, string detailsJson, CancellationToken ct)
    {
        // NOTE: only the secret NAME and the outcome are recorded — never the decrypted value.
        var evt = new AuditEvent
        {
            EventId = Guid.NewGuid(),
            OccurredAtUtc = _timeProvider.GetUtcNow(),
            Actor = _actorAccessor?.CurrentActor ?? SystemActor,
            Action = action,
            Outcome = outcome,
            Category = AuditCategory,
            Target = name.Value,
            DetailsJson = detailsJson,
        };

        return _audit.WriteAsync(evt, ct);
    }

    /// <summary>A cached decrypted secret and its expiry (revision kept for future invalidation).</summary>
    private readonly record struct CacheEntry(string Plaintext, DateTimeOffset ExpiresUtc, long Revision);
}
