using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using NLog.Extensions.Logging;
using ProfitGroup.NotifyService.Core.Auth;
using ProfitGroup.NotifyService.Core.Handlers;
using ProfitGroup.NotifyService.Data.Core.Data.Entities;
using ProfitGroup.NotifyService.Services;

namespace ProfitGroup.NotifyService.Core.Application
{
    public static class Extensions
    {
        public static WebApplicationBuilder AddLogger(this WebApplicationBuilder builder)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .Build();

            NLog.Config.LoggingConfiguration nlogConfig = new NLogLoggingConfiguration(config.GetSection("NLog"));

            builder.Services.AddLogging((options) => { options.AddNLog(nlogConfig); });

            return builder;
        }

        public static WebApplicationBuilder AddServices(this WebApplicationBuilder builder)
        {
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();


            builder.Services.AddAuthentication("BasicAuthentication").
                AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>
                    ("BasicAuthentication", null);

            builder.Services.AddDbContext<RDnLDatabaseContext>
                (options => options.UseSqlServer(builder.Configuration.GetConnectionString("RnDConnection")));

            builder.Services.AddTransient<Handlers.RouteHandler>();
            builder.Services.AddTransient<INotifyService, Services.NotifyService>();

            builder.Services.AddAuthorization();

            return builder;
        }

        public static WebApplication LoadSettings(this WebApplication app)
        {
            app.UseMiddleware<RequestScopedLoggerMiddleware>();
            
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseSwagger();
            app.UseSwaggerUI();
            
            app.RegisterRoutes();

            return app;
        }

        private static WebApplication RegisterRoutes(this WebApplication app)
        {
            // var handler = app.Services.GetService<Handlers.RouteHandler>()!;

            // app.MapPost("/handler", handler.TestHandler);

            app.MapPost("/S4IntegrationService/SoapIntegration", [Authorize](HttpContext context, Handlers.RouteHandler handler) =>
            {
                return handler.SoapIntegration(context);
            });
            app.MapPost("/SoapIntegration", [Authorize] (HttpContext context, Handlers.RouteHandler handler) =>
            {
                return handler.SoapIntegration(context);
            });

            return app;
        }
    }
}