using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using System.Text.Json;
using System.Text.Json.Serialization;
using WorkFlowCheck.DL;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using WorkFlowCheck.BL.Mappings;
using WorkFlowCheck.BL.Infra;
using WorkFlowCheck.DL.Seed;
using WorkFlowCheck.Common.RequestContext;
using WorkFlowCheck.API.RequestContext;
using WorkFlowCheck.API.Middleware;

var builder = WebApplication.CreateBuilder(args);

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .CreateLogger();

builder.Services.AddAutoMapper(typeof(MapperProfile));
builder.Services.AddMemoryCache();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<IRequestContext, HttpRequestContext>();

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connectionString, x => x.MigrationsAssembly("WorkFlowCheck.DL")));
//DI

DIConfig.DIInit(builder.Services);

// SWAGGER !!!
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "WorkFlowCheck API", Version = "v1" });

    // API Key Auth definíció
    c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
    {
        Description = "API Key szükséges. Használat: 'ApiKey: {kulcs}'",
        Name = "X-Api-Key", // A fejlécek között keresendő
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "ApiKey"
    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "ApiKey"
                },
                Scheme = "ApiKey",
                Name = "ApiKey",
                In = ParameterLocation.Header,
            },
            Array.Empty<string>()
        }
    });
});

builder.Host.UseSerilog();

builder.Services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        // Itt konfigurálhatod az egyedi beállításokat
        options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    });

builder.Services.AddCors(options =>
{ 
    options.AddDefaultPolicy(policy => 
    { 
    policy.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();   
    }); 
});

var app = builder.Build();
//----------------- Munkakönyvtárak létrehozása -----------------------------
string imageDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Images");
if (!Directory.Exists(imageDirectory))
{
    Directory.CreateDirectory(imageDirectory);
}
string pdfDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Pdf");

// Ensure the Images directory exists
if (!Directory.Exists(pdfDirectory))
{
    Directory.CreateDirectory(pdfDirectory);
}
//---------------------------------------------------------------------------


using (var scope = app.Services.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    DBInitializer.Seed(context);
}

// Swagger middleware
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "WorkFlowCheck API v1");
    });
}

// Routing és endpointok
//app.UseHttpsRedirection();
app.UseRouting();

app.UseMiddleware<ApiKeyMiddleware>();
app.UseMiddleware<JwtMiddleware>();

app.MapControllers();
app.UseAuthorization();
app.UseCors();
app.Run();

