using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using ReAct_PME.Application;
using ReAct_PME.Domain;
using ReAct_PME.Infrastructure;
using ReAct_PME.Infrastructure.Persistence;
using System.Text;



var builder = WebApplication.CreateBuilder(args);

builder.Configuration
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true)
    .AddEnvironmentVariables(); // ← prioritaire

var allowedOrigins = builder.Configuration
    .GetSection("Cors:AllowedOrigins")
    .Get<string[]>();

var secretKey = builder.Configuration["Jwt:SecretKey"];
if (!string.IsNullOrWhiteSpace(secretKey))
    Console.WriteLine($"JWT SecretKey length: {secretKey?.Length ?? 0}");

var environnement = builder.Configuration["Params:Environment"];
var apiUrl = builder.Configuration["Params:ApiUrl"];

if(apiUrl == null)
{
    apiUrl = "https://localhost:7008";
}
var isHttps = (apiUrl.ToLower().Contains("https://"));

Console.WriteLine($"ENV : {environnement}");
Console.WriteLine($"API : {apiUrl}");

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = 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(secretKey!))
    };
});

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

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddScoped<IDT_CONVERSATIONRepository, DT_CONVERSATIONRepository>();
builder.Services.AddScoped<IDT_CONVERSATIONService, DT_CONVERSATIONService>();
builder.Services.AddScoped<IDT_CONVERSATION_LIGNERepository, DT_CONVERSATION_LIGNERepository>();
builder.Services.AddScoped<IDT_CONVERSATION_LIGNEService, DT_CONVERSATION_LIGNEService>();
builder.Services.AddScoped<IDT_LOGSRepository, DT_LOGSRepository>();
builder.Services.AddScoped<IDT_LOGSService, DT_LOGSService>();

builder.Services.AddScoped<IDT_ROLERepository, DT_ROLERepository>();
builder.Services.AddScoped<IDT_ROLEService, DT_ROLEService>();
builder.Services.AddScoped<IDT_WORK_FORCERepository, DT_WORK_FORCERepository>();
builder.Services.AddScoped<IDT_WORK_FORCEService, DT_WORK_FORCEService>();
builder.Services.AddScoped<IDT_WORK_FORCE_ROLERepository, DT_WORK_FORCE_ROLERepository>();
builder.Services.AddScoped<IDT_WORK_FORCE_ROLEService, DT_WORK_FORCE_ROLEService>();

builder.Services.AddScoped<IListeMailsService, ListeMailsService>();
builder.Services.AddScoped<IChatRoomService, ChatRoomService>();
builder.Services.AddScoped<IVerifServices, VerifServices>();

builder.Services.AddScoped<IParametresService, ParametresService>();

builder.Services.AddScoped<IAuthRepository, AuthRepository>();
builder.Services.AddScoped<IAuthService, AuthService>();

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

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowBlazor", policy =>
    {
        policy.WithOrigins(allowedOrigins ?? Array.Empty<string>())
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});


builder.WebHost.UseUrls(apiUrl);

// ci-dessous : nécessaire avec docker / linux
if(environnement == "Docker")
{
    builder.WebHost.ConfigureKestrel(options =>
    {
        options.ListenAnyIP(80); // HTTP seulement
    });
}

builder.Services.Configure<KestrelServerOptions>(options =>
{
    options.Limits.MaxRequestBodySize = 1024 * 1024 * 100; // 100MB
});

var app = builder.Build();

app.Use(async (context, next) =>
{
    Console.WriteLine($"[Request] {context.Request.Method} {context.Request.Path}");
    await next.Invoke();
});


/*
// Migration auto de la base de données : PAS POUR L'INSTANT
using (var scope = app.Services.CreateScope())
{
    try{
         var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
         dbContext.Database.Migrate();

     }
     catch(Exception ex){
         Console.Writeline(ex.ToString()
     }
}
*/

app.UseRouting();
app.UseCors("AllowBlazor");

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

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
	app.UseSwagger();
	app.UseSwaggerUI();

    builder.Configuration.AddUserSecrets<Program>();
}

if(isHttps)
{
    app.UseHttpsRedirection();
    Console.WriteLine("HTTPS redirection is enabled. ");
}
else
{
    Console.WriteLine("Warning: HTTPS redirection is disabled. Ensure you are aware of the security implications.");
}
app.MapControllers();

app.Run();

                