using MyNewProjectName.Application;
using MyNewProjectName.Infrastructure;
using MyNewProjectName.WebAPI.Middleware;
using MyNewProjectName.WebAPI.Extensions;
using MyNewProjectName.Application.Interfaces;
using MyNewProjectName.WebAPI.Services;

var builder = WebApplication.CreateBuilder(args);

// ==========================================
// 1. ADD SERVICES TO CONTAINER
// ==========================================
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        // Configure enum serialization to use string representation
        options.JsonSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
    });
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddMemoryCache();
builder.Services.AddLogging();

// Extension Methods: Swagger, JWT Authentication & Authorization
builder.Services.AddCustomSwagger();
builder.Services.AddJwtAuthentication(builder.Configuration);
builder.Services.AddCustomAuthorization();

// Layers Registration
builder.Services.AddApplication();
builder.Services.AddInfrastructure(builder.Configuration);
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ICurrentUserService, CurrentUserService>();

// CORS Configuration
builder.Services.AddCors(option =>
{
    option.AddPolicy(name: "CorsPolicy",
        configurePolicy: builder => builder
        .SetIsOriginAllowed((host) => true)
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials());
});


builder.WebHost.UseUrls("http://0.0.0.0:5044");
var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(option =>
    {
        option.SwaggerEndpoint("/swagger/v1/swagger.json", "iYHCT360 API");
        option.RoutePrefix = "swagger"; // UI tại /swagger
        option.DisplayRequestDuration();
        option.EnableFilter();
        option.EnableValidator();
        option.EnableTryItOutByDefault();
    });
}


// Middleware Pipeline - Order is important!
// 1. CorrelationIdMiddleware: Generate correlation ID for request tracking (must be first)
app.UseMiddleware<CorrelationIdMiddleware>();

// 2. ExceptionHandlingMiddleware: Global exception handler (must be early to catch all exceptions)
app.UseMiddleware<ExceptionHandlingMiddleware>();

// 3. Routing & Static Files
app.UseRouting();
app.UseStaticFiles();

// 4. CORS (must be before UseAuthentication/UseAuthorization)
app.UseCors("CorsPolicy");

// 5. Authentication & Authorization
app.UseAuthentication();
app.UseAuthorization();

// 6. RequestResponseLoggingMiddleware: Log request/response (after routing and auth to avoid interfering with response)
app.UseMiddleware<RequestResponseLoggingMiddleware>();

// 7. Map Controllers
app.MapControllers();


app.Run();
