using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenWarehouse.auth.Common.ApiInterfeiceLib;

namespace OpenWarehouse.auth.lib;

public static class Waiter
{
    public static async Task<T> WaitForAut<T>(this T build, string? url, ILogger? logger)
        where T : IHostApplicationBuilder
    {

        if (logger == null)
            throw new NullReferenceException();
        
        var client = new OpenWarehouseAuthClient(url, new HttpClient());
    
        var i = 0;
        while(true)
        {
            try
            {
                var now = DateTime.UtcNow;
                var result = await client.PingAsync();
                
                logger.LogInformation(
                    $"Auth connected with Ping: {(DateTime.FromBinary(result.Time) - now).TotalMilliseconds}");

            }
            catch (Exception e)
            {
                if (i < 10)
                {
                    ++i;
                    logger.LogDebug($"Try {i} connect to auth fail.");
                    Thread.Sleep(10000);
                    continue;
                
                }

                logger.LogError($"Problem with auth service. \n " +
                                $"Mess: {e.Message}");
            }
            break;
        }
        
        return build;
    }
}