using System.Security.Principal;
using EnotaryoPH.Data;
using Exadel.Compreface.Clients.CompreFaceClient;
using Microsoft.AspNetCore.Authentication.Cookies;

namespace EnotaryoPH.Web
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
                options => options.LoginPath = new Microsoft.AspNetCore.Http.PathString("/Login"));
            builder.Services.AddAuthorization(options => options.AddPolicy("PrincipalPolicy", policy => policy.RequireRole("Principal")));
            var razorBuilder = builder.Services.AddRazorPages(options => options.Conventions.AuthorizeFolder("/Principal", "PrincipalPolicy"));
#if DEBUG
            razorBuilder.AddRazorRuntimeCompilation();
#endif

            builder.Services.AddDbContext<NotaryoDBContext>();
            builder.Services.AddHttpContextAccessor();
            builder.Services.AddSession(options => options.IdleTimeout = TimeSpan.FromMinutes(120));
            builder.Services.AddTransient<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>()?.HttpContext?.User);

            builder.Services.AddTransient<IPasswordService, PasswordService>();
            builder.Services.AddTransient<ICurrentUserService, CurrentUserService>();
            builder.Services.AddTransient<ICompreFaceClient>(provider =>
            {
                var config = provider.GetRequiredService<IConfiguration>();
                var host = config.GetValue<string>("CompreFaceConfig:Host");
                var port = config.GetValue<string>("CompreFaceConfig:Port");
                return new CompreFaceClient(host, port);
            });

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseSession();
            app.Use(async (context, next) =>
            {
                var key = "X-Session-ID";
                var value = context.Request.Cookies[key];
                if (string.IsNullOrEmpty(value))
                {
                    value = context.Session.Id;
                }

                if (string.IsNullOrEmpty(context.Session.GetString(key)))
                {
                    context.Session.SetString(key, value);
                }
                context.Response.Cookies.Append(key, value);
                await next.Invoke();
            });

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.MapStaticAssets();
            app.MapRazorPages()
               .WithStaticAssets();

            app.Run();
        }
    }
}