using Database.Database;
using Esim.SendMail.Services;
using Microsoft.EntityFrameworkCore;
using Esim.SendMail.Logging;
using Microsoft.Extensions.Logging;



namespace Esim.SendMail;


public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = Host.CreateApplicationBuilder(args);

        // Add configuration
        builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);


        // Configure logging
        builder.Logging.ClearProviders();
        builder.Logging.AddConsole();
        // Initialize and add Log4Net
        builder.Logging.AddLog4Net(Path.Combine(builder.Environment.ContentRootPath, "log4net.config"));
        builder.Logging.SetMinimumLevel(LogLevel.Information);

        // Add DbContext
        var connectionString = builder.Configuration["Connection"];
        builder.Services.AddDbContext<ModelContext>(options =>
            options.UseOracle(connectionString), ServiceLifetime.Transient);

        // Add Email Service as singleton for connection pooling
        builder.Services.AddSingleton<IEmailService, HighPerformanceEmailService>();

        // Add the background worker services
        builder.Services.AddHostedService<MessageQueueWorker>();
        builder.Services.AddHostedService<ExpiredMessageCleanupWorker>();

        var host = builder.Build();

        // Log startup info
        var logger = host.Services.GetRequiredService<ILogger<Program>>();
        var jobInterval = builder.Configuration["Job:IntervalSeconds"] ?? "10";
        
        logger.LogInformation("===========================================");
        logger.LogInformation("Esim.SendMail Service Starting...");
        logger.LogInformation("===========================================");
        logger.LogInformation("Job interval: {IntervalSeconds} seconds", jobInterval);
        logger.LogInformation("Service started successfully. Press Ctrl+C to stop.");

        await host.RunAsync();
    }
}
