using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OAuth;
using OAuthClient;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddConsole();

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

builder.Services.AddAuthentication(options => {
        options.DefaultAuthenticateScheme = "Cookie";
        options.DefaultChallengeScheme = "OAuth";
    })
    .AddCookie("Cookie", options => {
        options.Cookie.Name = "ClientCookie";
    })
    .AddOAuth("OAuth", options => {
        var authConfig = builder.Configuration.GetSection("Authentication:OAuth");

        options.ClientId = authConfig["ClientId"]!;
        options.ClientSecret = authConfig["ClientSecret"]!;
        options.CallbackPath = authConfig["CallbackPath"]!;
        options.AuthorizationEndpoint = authConfig["AuthorizationEndpoint"]!;
        options.TokenEndpoint = authConfig["TokenEndpoint"]!;
        options.SignInScheme = "Cookie";
        options.Backchannel = new HttpClient(new OriginHandler("http://localhost:5255"));

        options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "sub");

        options.Events = new OAuthEvents {
            OnCreatingTicket = context => {
                var payloadBase64 = context.AccessToken!.Split('.')[1];
                var payloadJson = Base64UrlTextEncoder.Decode(payloadBase64);
                var payload = JsonDocument.Parse(payloadJson);

                context.RunClaimActions(payload.RootElement);
                
                return Task.CompletedTask;
            }
        };
    });

builder.Services.AddAuthorization();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
    app.UseDeveloperExceptionPage();
} else {
    app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();

app.UseRouting();

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

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

app.Run();