using Serilog;
using Serilog.Events;

namespace JSMR.Api.Startup;

public static class HostBuilderExtensions
{
    public static IHostBuilder UseAppSerilog(this IHostBuilder host)
    {
        return host.UseSerilog((context, services, loggerConfiguration) =>
        {
            IConfiguration configuration = context.Configuration;
            IHostEnvironment environment = context.HostingEnvironment;

            loggerConfiguration
              .ReadFrom.Configuration(configuration)
              .ReadFrom.Services(services)
              .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
              .Enrich.WithProperty("Service", "JSMR.Api")
              .Enrich.WithProperty("Environment", environment.EnvironmentName);

            // Conditionally add Seq if configured correctly
            string? seqUrl = configuration["Seq:ServerUrl"];

            if (Uri.TryCreate(seqUrl, UriKind.Absolute, out _))
            {
                loggerConfiguration.WriteTo.Seq(seqUrl);
            }
        });
    }
}