using System.Security.Principal;
using Azure.Communication.CallAutomation;
using Azure.Communication.Identity;
using Azure.Communication.Rooms;
using Azure.Storage.Queues;
using Coravel;
using EnotaryoPH.Data;
using EnotaryoPH.Web.Common.Hubs;
using EnotaryoPH.Web.Common.Jobs;
using EnotaryoPH.Web.Common.Models;
using Exadel.Compreface.Clients.CompreFaceClient;
using Microsoft.AspNetCore.Authentication.Cookies;
using Syncfusion.Licensing;

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(nameof(UserType.Principal))));
            builder.Services.AddAuthorization(options => options.AddPolicy("ParticipantPolicy", policy => policy.RequireRole(nameof(UserType.Witness), nameof(UserType.Principal))));
            var razorBuilder = builder.Services.AddRazorPages(options =>
            {
                options.Conventions.AuthorizeFolder("/Principal", "PrincipalPolicy");
                options.Conventions.AuthorizeFolder("/Participant/Registration/Steps", "ParticipantPolicy");
                options.Conventions.AuthorizeFolder("/Participant/VideoCall");
            });
#if DEBUG
            razorBuilder.AddRazorRuntimeCompilation();
#endif
            builder.Services.AddSignalR();
            builder.Services.AddSingleton<INotificationService, NotificationService>();

            var config = builder.Configuration;
            builder.Services.AddTransient<IConfiguration, ConfigurationManager>(provider => config);

            SyncfusionLicenseProvider.RegisterLicense(config.GetValue<string>("SyncfusionLicenseKey"));

            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<Settings>(provider => new Settings
            {
                BaseUrl = config.GetValue<string>("BaseUrl") ?? ""
            });
            builder.Services.AddTransient<ISignInService, SignInService>();
            builder.Services.AddTransient<IPasswordService, PasswordService>();
            builder.Services.AddTransient<ICurrentUserService, CurrentUserService>();
            builder.Services.AddTransient<ICompreFaceClient>(provider =>
            {
                var host = config.GetValue<string>("CompreFaceConfig:Host");
                var port = config.GetValue<string>("CompreFaceConfig:Port");
                return new CompreFaceClient(host, port);
            });
            builder.Services.AddQueue();
            builder.Services.AddScheduler();
            builder.Services.AddMailer(config);
            builder.Services.AddTransient<SignatoryInvitationInvocable>();
            builder.Services.AddTransient<OneTimePasswordInvocable>();
            builder.Services.AddTransient<CheckRecordingAvailabilityInvocable>();
            builder.Services.AddTransient<IVideoConferenceService, VideoConferenceService>();
            builder.Services.AddTransient<IEventService, EventService>();
            builder.Services.AddScoped<RoomsClient>(provider =>
            {
                var connectionString = config.GetConnectionString("AzureCommunication");
                return string.IsNullOrEmpty(connectionString)
                    ? throw new InvalidConfigurationException("AzureCommunication", string.Empty)
                    : new RoomsClient(connectionString);
            });
            builder.Services.AddScoped<CommunicationIdentityClient>(provider =>
            {
                var connectionString = config.GetConnectionString("AzureCommunication");
                return string.IsNullOrEmpty(connectionString)
                    ? throw new InvalidConfigurationException("AzureCommunication", string.Empty)
                    : new CommunicationIdentityClient(connectionString);
            });
            builder.Services.AddScoped<CallAutomationClient>(provider =>
            {
                var connectionString = config.GetConnectionString("AzureCommunication");
                return string.IsNullOrEmpty(connectionString)
                    ? throw new InvalidConfigurationException("AzureCommunication", string.Empty)
                    : new CallAutomationClient(connectionString);
            });
            builder.Services.AddScoped<QueueClient>(provider =>
            {
                var connectionString = config.GetConnectionString("AzureStorage");
                return string.IsNullOrEmpty(connectionString)
                    ? throw new InvalidConfigurationException("AzureStorage", string.Empty)
                    : new QueueClient(connectionString, "recording-ready");
            });

            var app = builder.Build();

            app.Services.UseScheduler(scheduler => scheduler
                .Schedule<CheckRecordingAvailabilityInvocable>()
                .EveryTenSeconds());

            // 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.MapHub<NotificationHub>("/notificationHub");

            app.Run();
        }
    }
}