using System.Text.Json;
using Common.Global;
using Database.Database;
using log4net;
using log4net.Config;
using Microsoft.EntityFrameworkCore;
using SicboSub.Api.Business;
using SicboSub.Api.Singleton;

var builder = WebApplication.CreateBuilder(args);

// Initialize log4net
XmlConfigurator.Configure(new FileInfo(Path.Combine(builder.Environment.ContentRootPath, "log4net.config")));

// Set global configuration for use by singletons like ConfigManager
GlobalConfig.Configuration = builder.Configuration;

// Add services to the container.
builder.Services.AddControllersWithViews()
    .AddJsonOptions(options =>
    {
        // Use camelCase for JSON property names
        options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    });

// Add DbContext with Oracle provider
var connectionString = builder.Configuration.GetSection("Connection").Value;
builder.Services.AddDbContext<ModelContext>(options =>
    options.UseOracle(connectionString));

// Add Business Services
builder.Services.AddScoped<IPackageBusiness, PackageBusinessImpl>();
builder.Services.AddScoped<ISubscriptionBusiness, SubscriptionBusinessImpl>();
builder.Services.AddScoped<IGameBusiness, GameBusinessImpl>();
builder.Services.AddScoped<IUserBusiness, UserBusinessImpl>();
builder.Services.AddScoped<IExchangeBusiness, ExchangeBusinessImpl>();

// Add Auth Services
builder.Services.AddScoped<IAuthService, AuthServiceImpl>();
builder.Services.AddScoped<IAuthBusiness, AuthBusinessImpl>();

// Configure CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader();
    });
});

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Initialize ConfigManager to load configs from database
using (var scope = app.Services.CreateScope())
{
    var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
    try
    {
        logger.LogInformation("Initializing ConfigManager (Async)...");
        
        // Start background refresh task immediately
        // Does not block main thread prevents startup hang if DB connection fails
        Task.Run(() => ConfigManager.Instance.RefreshConfigs());
    }
    catch (Exception ex)
    {
        logger.LogError(ex, "Failed to initialize ConfigManager");
    }
}

// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI();

if (!app.Environment.IsDevelopment())
{
    app.UseHttpsRedirection();
}

app.UseRouting();
app.UseCors("AllowAll");
app.UseAuthorization();

app.MapControllers();

app.Run();
