using System.IdentityModel.Tokens.Jwt;
using FileAccessAgent.TestSite.Models;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();
builder.Services.AddHttpClient();
builder.Services.Configure<TestSiteAuthOptions>(builder.Configuration.GetSection(TestSiteAuthOptions.SectionName));
builder.Services.Configure<FileAccessAgentTestOptions>(builder.Configuration.GetSection(FileAccessAgentTestOptions.SectionName));

var authOptions = builder.Configuration.GetSection(TestSiteAuthOptions.SectionName).Get<TestSiteAuthOptions>()
    ?? new TestSiteAuthOptions();

if (string.IsNullOrWhiteSpace(authOptions.ClientId))
{
    throw new InvalidOperationException("MemberCenter:ClientId is required.");
}

JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

builder.Services
    .AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
    {
        options.Cookie.Name = ".FileAccessAgent.TestSite.Auth";
    })
    .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
    {
        options.Authority = authOptions.Authority;
        options.MetadataAddress = string.IsNullOrWhiteSpace(authOptions.MetadataAddress) ? null : authOptions.MetadataAddress;
        options.ClientId = authOptions.ClientId;
        options.ClientSecret = string.IsNullOrWhiteSpace(authOptions.ClientSecret) ? null : authOptions.ClientSecret;
        options.CallbackPath = authOptions.CallbackPath;
        options.SignedOutCallbackPath = authOptions.SignedOutCallbackPath;
        options.ResponseType = "code";
        options.UsePkce = true;
        options.SaveTokens = true;
        options.GetClaimsFromUserInfoEndpoint = true;
        options.RequireHttpsMetadata = authOptions.RequireHttpsMetadata;
        options.MapInboundClaims = false;

        options.Scope.Clear();
        foreach (var scope in authOptions.Scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
        {
            options.Scope.Add(scope);
        }
    });

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

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

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
