using System.Reflection;
using Email.Data;
using Email.Data.Repositories;
using Email.Data.Repositories.Contracts;
using Email.Data.Services;
using Api.Services;
using Microsoft.EntityFrameworkCore;
using Email.Models.Settings;
using Models.Settings;
using Serilog;
using StartupHelpers;

StartupExtensions.LoadDotEnvFile();

const string ServiceName = "email-api";
var appVersion = StartupExtensions.GetApplicationVersion(Assembly.GetExecutingAssembly());

try
{
    var builder = WebApplication.CreateBuilder(args);

    builder.ConfigureJsonSerilog(ServiceName, appVersion);
    Log.Information("Starting {Service} version {AppVersion}", ServiceName, appVersion);

    builder.AddAzureKeyVaultIfConfigured();

    builder.Services.AddControllers();
    builder.Services.AddSwaggerWithXmlComments(Assembly.GetExecutingAssembly(), "Email API");

    builder.Services.Configure<SmtpSettings>(builder.Configuration.GetSection("Smtp"));
    builder.Services.Configure<FileStorageSettings>(builder.Configuration.GetSection("FileStorage"));

    builder.Services.AddDbContext<EmailDbContext>(options =>
    {
        var connectionString = builder.Services.GetConfiguredDbConnectionString(builder.Configuration);
        options.UseSqlServer(connectionString, sql =>
        {
            sql.MigrationsHistoryTable(EmailDbContext.MigrationTableName, EmailDbContext.SchemaName);
            sql.MigrationsAssembly("email-data");
        });
    });

    builder.Services.AddScoped<IEmailTemplateRepository, EfEmailTemplateRepository>();
    builder.Services.AddSingleton<IEmailTemplateService, EmailTemplateService>();

    builder.Services.AddScoped<SmtpEmailDispatcher>();

    var app = builder.Build();

    app.LogStartupDiagnostics(ServiceName);

    app.UseDefaultSerilogRequestLogging();
    app.UseJsonExceptionHandler(ServiceName);
    app.UseInternalApiKeyProtection();
    app.UseSwaggerInDevelopment("Email API", "EmailAPI");

    app.UseRouting();
    app.UseAuthorization();
    app.MapControllers();

    Log.Information("Running EF Core migrations if any");
    using (var scope = app.Services.CreateScope())
    {
        var db = scope.ServiceProvider.GetRequiredService<EmailDbContext>();
        db.Database.Migrate();
    }

    Log.Information("{Service} startup complete. Listening for requests...", ServiceName);
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "{Service} terminated unexpectedly", ServiceName);
}
finally
{
    Log.Information("Shutting down {Service}", ServiceName);
    Log.CloseAndFlush();
}
