using songrequests_blazor.Components;
using Microsoft.EntityFrameworkCore;
using songrequests_blazor.Data;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using songrequests_blazor.Components.Account;
using NuGet.Configuration;
using songrequests_blazor.Settings;
using songrequests_blazor.Services;
using Microsoft.AspNetCore.Identity.UI.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

// Settings
builder.Services.Configure<Mailserver>(builder.Configuration.GetSection(nameof(Mailserver)));

// Database
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<LocalDbContext>(options => options.UseSqlite(connectionString));

// Authentication
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped<IdentityUserAccessor>();
builder.Services.AddScoped<IdentityRedirectManager>();
builder.Services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>();
builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = IdentityConstants.ApplicationScheme;
    options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies();

builder.Services.AddIdentityCore<IdentityUser>(options => {
    options.SignIn.RequireConfirmedAccount = false;
    options.SignIn.RequireConfirmedEmail = false;
    })
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<LocalDbContext>()
    .AddSignInManager()
    .AddDefaultTokenProviders();

// Email
builder.Services.AddTransient<IEmailSender<IdentityUser>, EmailSender>();

var googleAuth = builder.Configuration.GetSection("Authentication:Google");
if (googleAuth != null)
{
    builder.Services.AddAuthentication().AddGoogle(opt =>
    {
        opt.ClientId = googleAuth["ClientID"] ?? "";
        opt.ClientSecret = googleAuth["ClientSecret"] ?? "";
        opt.SignInScheme = IdentityConstants.ExternalScheme;
        opt.CallbackPath = "/signin-google";
    });
}

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // 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.UseHttpsRedirection();

app.UseStaticFiles();
app.UseAntiforgery();

app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

app.MapAdditionalIdentityEndpoints(); ;

app.Run();
