using Microsoft.EntityFrameworkCore;
using Meezi.Admin.API.Extensions;
using Meezi.Infrastructure.Data;
using Serilog;

namespace Meezi.Admin.API;

public class Program
{
    public static async Task Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .CreateLogger();

        try
        {
            var builder = WebApplication.CreateBuilder(args);
            builder.Host.UseSerilog((context, services, configuration) => configuration
                .ReadFrom.Configuration(context.Configuration)
                .ReadFrom.Services(services)
                .Enrich.FromLogContext()
                .WriteTo.Console());

            builder.Services.AddMeeziAdminServices(builder.Configuration);
            var app = builder.Build();
            app.ConfigureMeeziAdminPipeline();

            if (app.Configuration.GetValue<bool>("RUN_MIGRATIONS"))
            {
                await using var scope = app.Services.CreateAsyncScope();
                var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
                await db.Database.MigrateAsync();
                await DatabaseSchemaPatches.ApplyAsync(db);
            }

            if (!app.Configuration.GetValue<bool>("Testing:SkipSeed"))
                await PlatformDataSeeder.SeedAsync(app.Services);

            await app.RunAsync();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Admin API terminated unexpectedly");
        }
        finally
        {
            await Log.CloseAndFlushAsync();
        }
    }
}
