using System;
using System.IO;
using System.Threading.Tasks;

namespace StellaOps.Scanner.Sbomer.BuildXPlugin.Tests.TestUtilities;

internal sealed class TempDirectory : IDisposable, IAsyncDisposable
{
    public string Path { get; }

    public TempDirectory()
    {
        Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"stellaops-buildx-{Guid.NewGuid():N}");
        Directory.CreateDirectory(Path);
    }

    public void Dispose()
    {
        Cleanup();
        GC.SuppressFinalize(this);
    }

    public ValueTask DisposeAsync()
    {
        Cleanup();
        GC.SuppressFinalize(this);
        return ValueTask.CompletedTask;
    }

    private void Cleanup()
    {
        try
        {
            if (Directory.Exists(Path))
            {
                Directory.Delete(Path, recursive: true);
            }
        }
        catch
        {
            // Best effort cleanup only.
        }
    }
}
