using HoneyBox.Admin.Extensions;
using HoneyBox.Admin.Filters;
using HoneyBox.Admin.Business.Extensions;
using HoneyBox.Model.Data;
using Microsoft.EntityFrameworkCore;
using Scalar.AspNetCore;
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Configure Serilog
builder.Host.UseSerilog((context, services, configuration) => configuration
    .ReadFrom.Configuration(context.Configuration)
    .ReadFrom.Services(services)
    .Enrich.FromLogContext());

// Add services to the container
var mvcBuilder = builder.Services.AddControllers(options =>
{
    options.Filters.Add<AdminExceptionFilter>();
    options.Filters.Add<BusinessPermissionFilter>();
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddOpenApi();

// Add HoneyBox Admin services (DbContext, Services, JWT Authentication)
builder.Services.AddHoneyBoxAdmin(builder.Configuration);

// Add HoneyBoxDbContext for business database access
builder.Services.AddDbContext<HoneyBoxDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("BusinessConnection"));
});

// Add HoneyBox Admin Business services (Business Controllers and Services)
builder.Services.AddAdminBusiness(mvcBuilder);

builder.Services.AddAuthorization();

var app = builder.Build();

// 执行数据初始化
using (var scope = app.Services.CreateScope())
{
    var dataSeeder = scope.ServiceProvider.GetRequiredService<HoneyBox.Admin.Services.IDataSeeder>();
    await dataSeeder.SeedAsync();
}

// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
    app.MapScalarApiReference();
}

// Use HoneyBox Admin middleware (Static files, Authentication)
app.UseHoneyBoxAdmin();

app.UseRouting();

// Authorization must be between UseRouting and MapControllers
app.UseAuthorization();

app.MapControllers();

// SPA fallback - serve index.html for non-API routes
app.MapFallbackToFile("index.html");

app.Run();
