using Elastic.CommonSchema.Serilog;
using PARR.Core;
using PARR.DAL;
using PARR.Domain.Enums;
using PARR.Infrastructure;
using PARR.WorkloadBuilderWorker;
using PARR.WorkloadBuilderWorker.Settings;
using Serilog;

var builder = Host.CreateApplicationBuilder();

builder.Services.AddLogging(config =>
{
    config.ClearProviders();

    var logger = new LoggerConfiguration();

    if (builder.Environment.IsProduction())
        logger.WriteTo.Console(new EcsTextFormatter());
    else
        logger.WriteTo.Console();

    logger.ReadFrom.Configuration(builder.Configuration);

    config.AddSerilog(logger.CreateLogger());
});

var workerSettings = new WorkerSettings();
builder.Configuration.GetSection(nameof(WorkerSettings)).Bind(workerSettings);
builder.Services.AddSingleton(workerSettings);

#region PARR modules
builder.Services.AddDalServices(builder.Configuration);
builder.Services.AddCoreServices(builder.Configuration);
builder.Services.AddInfrastructureServices(builder.Configuration);
builder.Services.AddTaskManagement((provider, taskType) =>
{
    // Тут обрабатываем только задачи типа Workload
    if (taskType == TaskTypeEnum.Workload)
        return workerSettings.MqSettings;

    throw new ArgumentException($"Настройки для типа задания {taskType} не найдены в конфигурации.");
});

builder.Configuration.AddDalConfigurations(builder.Services);
builder.Services.AddDallSettings(builder.Configuration);
#endregion

// Задается через переменные окружеия
var runRabbit = builder.Configuration.GetValue<bool>("ENABLE_RABBIT", true);
var runInterval = builder.Configuration.GetValue<bool>("ENABLE_INTERVAL", true);

if (runRabbit)
{
    builder.Services.AddHostedService<RabbitWorker>();
}

if (runInterval)
{
    builder.Services.AddHostedService<IntervalWorker>();
}

// Настройка краша при ошибке. Если хоть один из воркеров упадет, то падает целиком проект
builder.Services.Configure<HostOptions>(options =>
{
    options.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.StopHost;
});

var host = builder.Build();
host.Run();
