#pragma warning disable AV1500
using System.Net;
using System.Reflection;
using CouchDB.Driver.DependencyInjection;
using MassTransit;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Server.DB;
using Server.Services;

var builder = Host.CreateApplicationBuilder();
var configurationRoot = builder.Configuration.AddJsonFile("settings.json", false, true)
    .AddEnvironmentVariables().Build();
builder.Services.AddLogging();
builder.Logging.AddFile("Logs/Server-{Date}.log", LogLevel.Debug);
builder.Logging.AddFile("Logs/Server-{Date}.json.log", LogLevel.Debug, isJson: true);
builder.Services.AddCouchContext<WonderkingContext>(cfg =>
{
    cfg.UseEndpoint(configurationRoot["DB:Endpoint"] ?? throw new InvalidOperationException())
        .UseBasicAuthentication(configurationRoot["DB:User"] ?? throw new InvalidOperationException(),
            configurationRoot["DB:Password"] ?? throw new InvalidOperationException())
        .EnsureDatabaseExists();
});
builder.Services.AddSingleton<PacketDistributorService>();
builder.Services.AddHostedService<PacketDistributorService>(provider =>
    provider.GetService<PacketDistributorService>() ?? throw new InvalidOperationException());
builder.Services.AddMassTransit(x =>
{
    x.UsingInMemory((context, configurator) => configurator.ConfigureEndpoints(context));
    x.AddMediator(cfg => cfg.AddConsumers(Assembly.GetExecutingAssembly()));
});
builder.Services.AddHostedService<WonderkingAuthServer>(provider => new WonderkingAuthServer(IPAddress.Any, 10001,
    provider.GetService<ILogger<WonderkingAuthServer>>() ?? throw new InvalidOperationException(),
    provider.GetService<IServiceProvider>() ?? throw new InvalidOperationException()));

using var host = builder.Build();
await host.RunAsync();
#pragma warning restore AV1500