using Apollinare.API.Hubs;
using Apollinare.API.Services;
using Apollinare.API.Services.Reports;
using Apollinare.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

// Database
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
    ?? "Data Source=apollinare.db";
builder.Services.AddDbContext<AppollinareDbContext>(options =>
    options.UseSqlite(connectionString));

// Services
builder.Services.AddScoped<EventoCostiService>();
builder.Services.AddScoped<DemoDataService>();
builder.Services.AddScoped<ReportGeneratorService>();
builder.Services.AddScoped<ModuleService>();
builder.Services.AddSingleton<DataNotificationService>();

// Memory cache for module state
builder.Services.AddMemoryCache();

// SignalR - with increased message size for template sync (default is 32KB)
builder.Services.AddSignalR(options =>
    {
        options.MaximumReceiveMessageSize = 1024 * 1024; // 1MB max message size
    })
    .AddJsonProtocol(options =>
    {
        options.PayloadSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
        options.PayloadSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    });

// CORS - Allow credentials for SignalR (accepts any origin for external access)
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowFrontend", policy =>
    {
        policy.SetIsOriginAllowed(_ => true) // Permette qualsiasi origine
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials();
    });
});

// Controllers with JSON options
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
        options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    });

builder.Services.AddOpenApi();

var app = builder.Build();

// Initialize database
if (app.Environment.IsDevelopment())
{
    using var scope = app.Services.CreateScope();
    var db = scope.ServiceProvider.GetRequiredService<AppollinareDbContext>();
    db.Database.EnsureCreated();
    DbSeeder.Seed(db);

    // Seed default modules
    var moduleService = scope.ServiceProvider.GetRequiredService<ModuleService>();
    await moduleService.SeedDefaultModulesAsync();

    app.MapOpenApi();
}

app.UseCors("AllowFrontend");
app.UseWebSockets();
app.UseAuthorization();
app.MapControllers();
app.MapHub<DataHub>("/hubs/data");
app.MapHub<CollaborationHub>("/hubs/collaboration");

app.Run();
