using Expedience.Api.Consumers;
using Expedience.Infrastructure;
using Expedience.Api.Encryption;
using MassTransit;
using Microsoft.EntityFrameworkCore;
using Expedience.Infrastructure.Concurrency;

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("Expedience");
builder.Services.AddDbContext<ExpedienceContext>(options =>
    options.UseNpgsql(connectionString).UseLowerCaseNamingConvention());

builder.Services.AddControllers();

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

var rabbitMqHost = builder.Configuration.GetSection("RabbitMq")["Host"];
var userName = builder.Configuration.GetSection("RabbitMq")["UserName"];
var password = builder.Configuration.GetSection("RabbitMq")["Password"];
builder.Services.AddMassTransit(opt =>
{ 
    opt.AddConsumersFromNamespaceContaining<DutyCompletionResultConsumer>();
    
    opt.UsingRabbitMq((context, cfg) =>
    {
        cfg.Host(rabbitMqHost, h =>
        {
            h.Username(userName);
            h.Password(password);
        });
        cfg.ConfigureEndpoints(context);
    });
});

builder.Services.AddEnyimMemcached();
builder.Services.AddScoped<IExpedienceRepository, ExpedienceRepository>();

builder.Services.AddSingleton<IDistributedLock, DistributedLock>();
builder.Services.AddSingleton<IDecryptor, Decryptor>();

var app = builder.Build();

var scope = app.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<ExpedienceContext>();

dbContext.Database.EnsureCreated();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();
