using System.Reflection;
using Api.Services;
using Api.Services.Contracts;
using Models.Settings;
using Refit;
using Serilog;
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<SmtpSettings>(builder.Configuration.GetSection("Smtp"));
    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.AddHttpClient<ICaptchaVerifier, RecaptchaVerifier>();
    builder.Services.AddSingleton<IEmailSender, SmtpEmailSender>();
    builder.Services.AddSingleton<Microsoft.AspNetCore.StaticFiles.IContentTypeProvider, Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider>();

    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<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("{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();
}
