using System.Text;
using Knots;
using FastEndpoints;
using FastEndpoints.Swagger;
using Knots.Hubs;
using Knots.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

// On ajoute ici la configuration de la base de données
builder.Services.AddDbContext<KnotsDbContext>();

//On ajoute le CORS au code
builder.Services.AddCors(options =>
{ options.AddDefaultPolicy(policyBuilder =>
    {
        policyBuilder
            .WithOrigins("http://localhost:5250", "http://localhost:4200")
            .WithMethods("GET", "POST", "PUT", "PATCH", "DELETE")
            .AllowAnyHeader();
    });
});

builder.Services.AddFastEndpoints(o =>
{
    o.DisableAutoDiscovery = false;
});

builder.Services.SwaggerDocument();

builder.Services.AddScoped<JwtService>();

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!))
        };
    });
builder.Services.AddAuthorization();

builder.Services.AddSignalR();

builder.Services.AddAutoMapper(cfg => { }, typeof(Program).Assembly);

// On construit l'application en lui donnant vie
WebApplication app = builder.Build();

app.MapHub<ChatHub>("hubs/chat");

app.UseCors();

app.UseHttpsRedirection();

app.UseAuthentication()
    .UseAuthorization()
    .UseFastEndpoints(options => 
        { 
            options.Endpoints.RoutePrefix = "API";
            options.Endpoints.ShortNames = true;
        }
    ).UseSwaggerGen();


app.Run();