using MediatR;
using MediatR.Pipeline;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Netmash.Extensions.Swagger;
using Netmash.Extensions.Swagger.Constants;
using Netmash.Security.Authentication.Tuitio;
using NetworkResurrector.Agent.Application;
using System.Reflection;

namespace NetworkResurrector.Agent.Extensions
{
    public static class StartupExtensions
    {
        public static void ConfigureServices(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddControllers();

            // Add basic authentication 
            services.AddTuitioAuthentication(configuration.GetSection("Tuitio")["BaseAddress"]);

            // MediatR
            services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Application.Queries.GetSystemVersion>());
            services.AddScoped(typeof(IPipelineBehavior<,>), typeof(RequestPreProcessorBehavior<,>));
            services.AddScoped(typeof(IPipelineBehavior<,>), typeof(RequestPostProcessorBehavior<,>));

            // AutoMapper
            services.AddAutoMapper(typeof(Application.Mappings.MappingProfile).Assembly);

            // Swagger
            var agentCode = configuration.GetValue<string>("Agent:Code");
            services.AddSwagger($"NetworkResurrectorAgent {agentCode}", AuthorizationType.Tuitio);

            // Data access
            //  services.AddDataAccess();

            // Application
            services.AddApplicationServices();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public static void Configure(this IApplicationBuilder app, IConfiguration configuration)
        {
            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            var agentCode = configuration.GetValue<string>("Agent:Code");
            app.ConfigureSwagger($"NetworkResurrectorAgent {agentCode}");
        }
    }
}
