using Atomx.Admin.Client.Services;
using Atomx.Admin.Client.Utils;
using Atomx.Admin.Components;
using Atomx.Admin.Extensions;
using Atomx.Admin.Middlewares;
using Atomx.Admin.Models;
using Atomx.Admin.Services;
using Atomx.Admin.Utils;
using Atomx.Common.Models;
using Atomx.Data;
using Atomx.Data.Services;
using Atomx.Utils.Json.Converts;
using Blazored.LocalStorage;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.EntityFrameworkCore;
using Scalar.AspNetCore;
using Serilog;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;

var builder = WebApplication.CreateBuilder(args);

// 配置 Serilog
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .Enrich.FromLogContext()
    .CreateLogger();

// Add services to the container.
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents()
    .AddInteractiveWebAssemblyComponents();



builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
    options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    options.JsonSerializerOptions.Converters.Add(new LongJsonConverter());
});

builder.Services.AddRouting(p => p.LowercaseUrls = true);

builder.Services.AddMapster();
builder.Services.AddBlazoredLocalStorage();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddHttpContextAccessor();
// 注册授权处理器
builder.Services.AddScoped<IPermissionService, PermissionService>();
builder.Services.AddScoped<IAuthorizationHandler, PermissionAuthorizationHandler>();

builder.Services.AddScoped<AuthenticationStateProvider, PersistingRevalidatingAuthenticationStateProvider>();
builder.Services.AddScoped<AuthenticationStateProvider, PersistentAuthenticationStateProvider>();

builder.Services.AddScoped<IIdCreatorService, IdCreatorService>();
builder.Services.AddScoped<IdentityService, IdentityService>();
builder.Services.AddScoped<ILocalizationService, LocalizationService>();
builder.Services.AddScoped<LocalizationFile, LocalizationFile>();
builder.Services.AddScoped<ITokenProvider, ServerTokenProvider>();
builder.Services.AddScoped<AuthHeaderHandler>();

builder.Services.AddHttpClientApiService(builder.Configuration["WebApi:ServerUrl"] ?? "http://localhost");
builder.Services.AddDataService();
builder.Services.AddAuthorize(builder.Configuration);

var connection = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<DataContext>(options => options.UseNpgsql(connection, p => p.MigrationsHistoryTable("__DbMigrationsHistory")));


builder.Services.AddStackExchangeRedisCache(options =>
{
    #region
    options.Configuration = $"{builder.Configuration.GetConnectionString("cache")}";
    options.InstanceName = builder.Configuration["RedisCache:InstanceName"];
    #endregion
});

builder.Services.AddOpenApi();

builder.Services.AddAntDesign();

builder.Services.Configure<MonitoringOptions>(builder.Configuration.GetSection("Monitoring"));

var app = builder.Build();

app.AddDataMigrate();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseWebAssemblyDebugging();
    app.MapScalarApiReference(); // 映射其他参考路径
    app.MapOpenApi(); // 映射 OpenAPI 文档路径
}
else
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
}



app.UseCors(option =>
{
    option.AllowAnyOrigin();
    option.AllowAnyMethod();
    option.AllowAnyHeader();
});

app.UseStaticFiles();

app.UseAuthentication();
app.UseAuthorization();

app.UseAntiforgery();
app.MapStaticAssets();

app.UseMiddleware<MonitoringMiddleware>();


app.MapControllers();
app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode()
    .AddInteractiveWebAssemblyRenderMode()
    .AddAdditionalAssemblies(typeof(Atomx.Admin.Client._Imports).Assembly);

app.Run();
