namespace qdr.fnd.core.pqueue.fnd.candidates
{
    public class TimeoutUtils
    {
        public static async Task ExecuteWithTimeoutAsync(Action action, TimeSpan timeout)
        {
            using var cts = new CancellationTokenSource();
            var task = Task.Run(action, cts.Token);

            try
            {
                if (await Task.WhenAny(task, Task.Delay(timeout, cts.Token)) == task)
                {
                    // Task completed within the timeout
                    await task; // Propagate any exceptions
                }
                else
                {
                    // Timeout occurred
                    cts.Cancel();
                    throw new TimeoutException($"The operation has timed out after {timeout.TotalSeconds} seconds.");
                }
            }
            catch(Exception){
                throw;
            }
            finally
            {
                cts.Cancel(); // Ensure we always cancel the CancellationTokenSource
            }
        }
    }
}
