namespace Hims.Api.Extensions
{
    using System.Reflection;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Hosting;
    using Middleware;

    using Hims.Api.Hubs;
    using Microsoft.AspNetCore.Http.Connections;
    using Hangfire;

    /// <summary>
    /// The app builder extensions.
    /// </summary>
    public static class AppBuilderExtensions
    {
        /// <summary>
        /// The register application builder.
        /// </summary>
        /// <param name="app">
        /// The application builder.
        /// </param>
        /// <param name="env">
        /// The environment.
        /// </param>
        /// <param name="configuration">
        /// The configuration.
        /// </param>
        /// <param name="assembly">
        /// The assembly.
        /// </param>
        /// <returns>
        /// The <see cref="IApplicationBuilder"/>.
        /// </returns>
        public static IApplicationBuilder Register(this IApplicationBuilder app, IWebHostEnvironment env, IConfiguration configuration, Assembly assembly)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/home/error");

                app.Use(async (ctx, next) =>
                {
                    await next();
                    if (ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
                    {
                        ctx.Request.Path = "/home/notfound";
                        await next();
                    }
                });
            }
            app.UseCors("CorsPolicy");
            app.UseRouting();
            app.UseStaticFiles();

            AuthenticationMiddleware.Configure(app);
            SwaggerMiddleware.Configure(app, configuration, assembly);

            app.UseAuthorization();
            

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllers();
                endpoints.MapHub<CommunicationHub>("/communication", options =>
                {
                    options.Transports = HttpTransportType.ServerSentEvents | HttpTransportType.WebSockets;
                });
            });

            return app;
        }
    }
}