using ReportingServices.API.Models;
using ReportingServices.Shared.Repositories;
using Serilog;

namespace ReportingServices.API;

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", appSettings.LoggingDirectory);
        _ = 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.AddControllers();
        // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
        _ = builder.Services.AddEndpointsApiExplorer();
        _ = builder.Services.AddSwaggerGen();
        _ = builder.Services.AddSingleton(_ => appSettings);
        _ = builder.Services.AddScoped<IScrapeDatabaseRepository, ScrapeDatabaseRepository>(_ => new(appSettings.ConnectionString));

        WebApplication app = builder.Build();

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            _ = app.UseSwagger();
            _ = app.UseSwaggerUI();
        }

        _ = app.UseHttpsRedirection();

        _ = app.UseAuthorization();

        _ = app.MapControllers();
        _ = app.Lifetime.ApplicationStopped.Register(Log.CloseAndFlush);
        log.Information("Starting Web APIs");

        try
        {
            app.Run();
        }
        catch (Exception ex)
        {
            log.Fatal(ex, "Host terminated unexpectedly");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
}