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

StartupExtensions.LoadDotEnvFile();

const string ServiceName = "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.Configure<GoogleSettings>(builder.Configuration.GetSection("Google"));
    builder.Services.Configure<ContactSettings>(builder.Configuration.GetSection("Contact"));
    builder.Services.Configure<SubscribeSettings>(builder.Configuration.GetSection("Subscribe"));
    builder.Services.Configure<CaptchaSettings>(builder.Configuration.GetSection("Captcha"));
    builder.Services.Configure<FileStorageSettings>(builder.Configuration.GetSection("FileStorage"));
    builder.Services.Configure<JobSearchLinkSettings>(builder.Configuration.GetSection("JobSearch"));
    builder.Services.Configure<EmailApiSettings>(builder.Configuration.GetSection("EmailApi"));

    builder.Services.AddDbContext<MyAiDbContext>(options =>
    {
        var connectionString = builder.Services.GetConfiguredDbConnectionString(builder.Configuration);
        options.UseSqlServer(connectionString, sql =>
        {
            sql.MigrationsAssembly("myai-data");
            sql.MigrationsHistoryTable(MyAiDbContext.MigrationTableName, MyAiDbContext.SchemaName);
        });
    });
    builder.Services.AddSingleton<ITemplateService, DbTemplateService>();

    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.AddHttpClient<ICaptchaVerifier, RecaptchaVerifier>();
    builder.Services.AddSingleton<IEmailSender, EmailApiEmailSender>();
    builder.Services.AddSingleton<Microsoft.AspNetCore.StaticFiles.IContentTypeProvider, Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider>();

    static void ConfigureEmailApiClient(IServiceProvider sp, HttpClient client)
    {
        var config = sp.GetRequiredService<IConfiguration>();
        var baseUrl = config["EmailApi:BaseUrl"] ?? string.Empty;
        if (!string.IsNullOrWhiteSpace(baseUrl))
            client.BaseAddress = new Uri(baseUrl.TrimEnd('/') + "/");
        var key = config["EmailApi:InternalApiKey"];
        if (!string.IsNullOrWhiteSpace(key) && !client.DefaultRequestHeaders.Contains("X-Internal-Api-Key"))
            client.DefaultRequestHeaders.Add("X-Internal-Api-Key", key);
    }

    static void ConfigureCvMatcherApiClient(IServiceProvider sp, HttpClient client)
    {
        var config = sp.GetRequiredService<IConfiguration>();
        var baseUrl = config["CvMatcherApi:BaseUrl"] ?? string.Empty;
        if (!string.IsNullOrWhiteSpace(baseUrl))
            client.BaseAddress = new Uri(baseUrl.TrimEnd('/') + "/");
        var key = config["CvMatcherApi:InternalApiKey"];
        if (!string.IsNullOrWhiteSpace(key) && !client.DefaultRequestHeaders.Contains("X-Internal-Api-Key"))
            client.DefaultRequestHeaders.Add("X-Internal-Api-Key", key);
    }

    builder.Services.AddRefitClient<IEmailApiClient>()
        .ConfigureHttpClient(ConfigureEmailApiClient);

    builder.Services.AddRefitClient<Api.Clients.Api.Contracts.ICvMatcherApi>()
        .ConfigureHttpClient(ConfigureCvMatcherApiClient);

    builder.Services.AddRefitClient<Api.Clients.Api.Contracts.IJobSearchApi>()
        .ConfigureHttpClient(ConfigureCvMatcherApiClient);

    builder.Services.AddSwaggerWithXmlComments(Assembly.GetExecutingAssembly(), "API");
    builder.Services.ConfigureCaddyForwardedHeaders();
    builder.Services.AddFrontendCorsFromConfiguration(builder.Configuration);
    builder.Services.AddPublicApiRateLimiting(builder.Configuration);

    var app = builder.Build();

    app.LogStartupDiagnostics(ServiceName);

    app.UseForwardedHeaders();
    app.UseDefaultSerilogRequestLogging(includeProxyHeaders: true);
    app.UseSwaggerInDevelopment("API", "API");

    app.UseHttpsRedirection();
    app.UseAuthorization();
    app.UseRouting();
    app.UseCors("FrontendOnly");
    app.UseRateLimiter();
    app.MapControllers();

    Log.Information("Running EF Core migrations if any");
    using (var scope = app.Services.CreateScope())
    {
        var db = scope.ServiceProvider.GetRequiredService<MyAiDbContext>();
        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();
}
