using Microsoft.EntityFrameworkCore;
using EonaCat.LogStack.Status.Data;
using EonaCat.LogStack.Status.Services;

// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromHours(8);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

var dbPath = Path.Combine(builder.Environment.ContentRootPath, "EonaCat.LogStack.Status.db");
builder.Services.AddDbContextFactory<DatabaseContext>(options => options.UseSqlite($"Data Source={dbPath}"));

// Register DatabaseContext directly as well (for controllers that inject it directly)
builder.Services.AddDbContext<DatabaseContext>(options => options.UseSqlite($"Data Source={dbPath}"));

builder.Services.AddScoped<MonitoringService>();
builder.Services.AddScoped<AuthenticationService>();
builder.Services.AddScoped<IngestionService>();
builder.Services.AddHostedService<SyslogUdpService>();
builder.Services.AddHostedService<MonitoringBackgroundService>();
builder.Services.AddControllers();

var app = builder.Build();

// Ensure database is created and apply any pending migrations
using (var scope = app.Services.CreateScope())
{
    var database = scope.ServiceProvider.GetRequiredService<IDbContextFactory<DatabaseContext>>().CreateDbContext();
    database.Database.EnsureCreated();
}

app.UseStaticFiles();
app.UseRouting();
app.UseSession();
app.MapRazorPages();
app.MapControllers();

app.Run();
