using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Identity;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using SecureSharing.Business.Infrastructure;
using SecureSharing.Business.Infrastructure.Extensions;
using SecureSharing.Business.Infrastructure.Settings;
using SecureSharing.Business.Interfaces;
using SecureSharing.Business.Services;
using SecureSharing.Data.DbContexts;
using SecureSharing.Infrastructure;
using SecureSharing.Infrastructure.Middleware;
using SecureSharing.Quartz;

var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
var services = builder.Services;

StartupConfiguration.ConfigureStartupConfig<EmailSettings>(services, configuration);
services.AddControllersWithViews();
services.AddRazorPages();
StartupExtensions.ConfigureServices(services);
services.AddDefaultIdentity<IdentityUser>(options => { options.SignIn.RequireConfirmedAccount = false; })
    .AddDefaultUI()
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<AppDbContext>();

services.AddScoped<IMessageService, MessageService>();
services.AddScoped<IModelFactory, ModelFactory>();

services.AddAuthentication(o => { o.DefaultScheme = GoogleDefaults.AuthenticationScheme; })
    .AddGoogle(options =>
    {
        options.ClientId = configuration["EmailSettings:ClientId"];
        options.ClientSecret = configuration["EmailSettings:ClientSecret"];
    });

// Add Quartz services
services.AddSingleton<IJobFactory, JobFactory>();
services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();

// Add our jobs
services.AddScoped<MessageDeletionJob>();
services.AddSingleton(new JobMetadata(
    typeof(MessageDeletionJob),
    "0 10 09 * * ?"));

services.AddHostedService<JobsService>();

var app = builder.Build();

if (builder.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/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.UseCookiePolicy(new CookiePolicyOptions
{
    MinimumSameSitePolicy = SameSiteMode.Lax
});

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.UseMiddleware(typeof(ExceptionHandlingMiddleware));

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        "default",
        "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();
});

app.Run();