using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using NetworkResurrector.Api.Extensions;
using Serilog;
using System;

namespace NetworkResurrector.Api
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            builder.Host.UseSerilog((_, lc) =>
            {
                lc
                .ReadFrom.Configuration(builder.Configuration)
                .Enrich.FromLogContext()
                .WriteTo.Console()
                .WriteTo.ConfiguredDestinations(builder.Configuration);
            });

            builder.Services.ConfigureServices(builder.Configuration);

            var app = builder.Build();
            app.Configure();

            var exitCode = 0;
            try
            {
                var urls = builder.Configuration.GetValue<string>("Urls");
                Log.Information("Starting network resurrector API...");
                Log.Information($"Network resurrector API listening on {urls}");
                Console.WriteLine("Application started. Press Ctrl+C to shut down.");

                app.Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Network resurrector API host terminated unexpectedly");
                exitCode = 1;
            }
            finally
            {
                Log.CloseAndFlush();
            }
            Environment.Exit(exitCode);
        }
    }
}
