using ReportingServices.UI.Models;
using Serilog;

namespace ReportingServices.UI;

public class Program
{
    private static void Main(string[] args)
    {
        LoggerConfiguration loggerConfiguration = new();

        WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
        _ = builder.Configuration.AddUserSecrets<Program>();
        AppSettings appSettings = Models.Binder.AppSettings.Get(builder.Configuration);
        Environment.SetEnvironmentVariable("workingDirectory", "D:\\tmp\\logging\\MesaReportingServices\\UI");
        _ = loggerConfiguration.ReadFrom.Configuration(builder.Configuration);
        _ = builder.Host.UseSerilog();
        Log.Logger = loggerConfiguration.CreateLogger();
        Serilog.ILogger log = Log.ForContext<Program>();

        // Add services to the container.
        _ = builder.Services.AddControllersWithViews();
        _ = builder.Services.AddSingleton(_ => appSettings);

        WebApplication app = builder.Build();

        // Configure the HTTP request pipeline.
        if (!app.Environment.IsDevelopment())
        {
            _ = app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            _ = app.UseHsts();
        }

        _ = app.UseHttpsRedirection();
        _ = app.UseStaticFiles();

        _ = app.UseRouting();

        _ = app.UseAuthorization();

        _ = app.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        _ = app.Lifetime.ApplicationStopped.Register(Log.CloseAndFlush);
        log.Information("Starting Web Application");
        try
        {
            app.Run();
        }
        catch (Exception ex)
        {
            log.Fatal(ex, "Host terminated unexpectedly");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
}