namespace JobTrackerApi.Services;

public interface IStartupReadiness
{
    Task WaitUntilReadyAsync(CancellationToken cancellationToken);
    void MarkReady();
}

public sealed class StartupReadiness : IStartupReadiness
{
    private readonly TaskCompletionSource<bool> _ready = new(TaskCreationOptions.RunContinuationsAsynchronously);

    public Task WaitUntilReadyAsync(CancellationToken cancellationToken)
    {
        if (_ready.Task.IsCompleted)
        {
            return Task.CompletedTask;
        }

        return _ready.Task.WaitAsync(cancellationToken);
    }

    public void MarkReady()
    {
        _ready.TrySetResult(true);
    }
}
