using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using PlaylistShared.Data.Contexts;
using PlaylistShared.Data.Entities;
using PlaylistShared.Services;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();

builder.Services.AddDbContext<AppDbContext>(options =>
{
    options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
});

builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<AppDbContext>()
    .AddDefaultTokenProviders();

builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Login";
    options.LogoutPath = "/Logout";
    options.AccessDeniedPath = "/AccessDenied";
});

builder.Services.AddAuthentication()
    .AddOAuth("Yandex", options =>
    {
        options.ClientId = builder.Configuration["YandexOAuth:ClientId"];
        options.ClientSecret = builder.Configuration["YandexOAuth:ClientSecret"];
        options.AuthorizationEndpoint = builder.Configuration["YandexOAuth:AuthorizationEndpoint"];
        options.TokenEndpoint = builder.Configuration["YandexOAuth:TokenEndpoint"];
        options.UserInformationEndpoint = builder.Configuration["YandexOAuth:UserInfoEndpoint"];
        options.CallbackPath = "/signin-yandex";

        options.ClaimActions.MapJsonKey("urn:yandex:avatar_url", "avatar_url");
        options.ClaimActions.MapJsonKey("urn:yandex:display_name", "display_name");

        options.Events = new Microsoft.AspNetCore.Authentication.OAuth.OAuthEvents
        {
            OnCreatingTicket = async context =>
            {
                var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", context.AccessToken);
                var response = await context.Backchannel.SendAsync(request);
                response.EnsureSuccessStatusCode();
                var user = System.Text.Json.JsonDocument.Parse(await response.Content.ReadAsStringAsync());
                context.RunClaimActions(user.RootElement);
            }
        };
    });

builder.Services.AddScoped<IYandexMusicService, YandexMusicService>();
builder.Services.AddHttpClient();

var app = builder.Build();

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

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

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

app.MapRazorPages();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();