using System;
using System.Threading;

namespace StellaOps.Feedser.Exporter.TrivyDb;

internal sealed record TrivyDbExportOverrides(
    bool? PublishFull,
    bool? PublishDelta,
    bool? IncludeFull,
    bool? IncludeDelta)
{
    public bool HasOverrides =>
        PublishFull.HasValue || PublishDelta.HasValue || IncludeFull.HasValue || IncludeDelta.HasValue;
}

internal static class TrivyDbExportOverrideScope
{
    private sealed class Scope : IDisposable
    {
        private readonly TrivyDbExportOverrides? _previous;
        private bool _disposed;

        public Scope(TrivyDbExportOverrides? previous)
        {
            _previous = previous;
        }

        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            _disposed = true;
            CurrentOverrides.Value = _previous;
        }
    }

    private static readonly AsyncLocal<TrivyDbExportOverrides?> CurrentOverrides = new();

    public static TrivyDbExportOverrides? Current => CurrentOverrides.Value;

    public static IDisposable Begin(TrivyDbExportOverrides overrides)
    {
        var previous = CurrentOverrides.Value;
        CurrentOverrides.Value = overrides;
        return new Scope(previous);
    }
}
