using Autofac;
using Autofac.Extensions.DependencyInjection;

using HoneyBox.Api.BackgroundServices;
using HoneyBox.Api.Filters;
using HoneyBox.Core.Mappings;
using HoneyBox.Infrastructure.Cache;
using HoneyBox.Infrastructure.Modules;
using HoneyBox.Model.Data;
using HoneyBox.Model.Models.Auth;
using HoneyBox.Model.Models.Payment;

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

using Scalar.AspNetCore;

using Serilog;

using System.Text;

// 配置 Serilog
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
        .Build())
    .CreateLogger();

try
{
    Log.Information("Starting HoneyBox API...");

    var builder = WebApplication.CreateBuilder(args);

    // 使用 Serilog
    builder.Host.UseSerilog();

    // 使用 Autofac 作为依赖注入容器
    builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
    builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
    {
        // 注册基础设施模块
        containerBuilder.RegisterModule<InfrastructureModule>();
        // 注册服务模块
        containerBuilder.RegisterModule<ServiceModule>();
    });

    // 配置 DbContext
    builder.Services.AddDbContext<HoneyBoxDbContext>(options =>
    {
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
    });

    // 配置 JWT 设置
    var jwtSettings = new JwtSettings();
    builder.Configuration.GetSection("JwtSettings").Bind(jwtSettings);
    builder.Services.AddSingleton(jwtSettings);

    // 配置高德地图设置
    var amapSettings = new AmapSettings();
    builder.Configuration.GetSection("AmapSettings").Bind(amapSettings);
    builder.Services.AddSingleton(amapSettings);

    // 配置应用程序设置（测试环境等）
    var appSettings = new AppSettings();
    builder.Configuration.GetSection("AppSettings").Bind(appSettings);
    builder.Services.AddSingleton(appSettings);

    // 配置微信支付设置
    builder.Services.Configure<WechatPaySettings>(builder.Configuration.GetSection("WechatPaySettings"));

    // 注册 HttpClient 用于微信服务
    builder.Services.AddHttpClient();

    // 配置 JWT 认证
    var key = Encoding.ASCII.GetBytes(jwtSettings.Secret);
    builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = true,
            ValidIssuer = jwtSettings.Issuer,
            ValidateAudience = true,
            ValidAudience = jwtSettings.Audience,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };
    });

    // 配置 Mapster
    builder.Services.AddMapsterConfiguration();

    // 注册 Redis 缓存服务（通过 Autofac 模块注册，这里添加 IConfiguration）
    builder.Services.AddSingleton<ICacheService>(sp =>
        new RedisCacheService(builder.Configuration));

    // 注册福利屋开奖后台服务
    builder.Services.AddHostedService<WelfareLotteryService>();

    // 注册微信发货重试后台服务
    builder.Services.AddHostedService<HoneyBox.Core.Services.ShippingRetryBackgroundService>();

    // 添加控制器
    builder.Services.AddControllers(options =>
    {
        // 添加全局异常过滤器
        options.Filters.Add<GlobalExceptionFilter>();
    });

    // 配置 OpenAPI（.NET 10 内置支持）
    builder.Services.AddOpenApi(options =>
    {
        // 添加文档信息
        options.AddDocumentTransformer((document, context, ct) =>
        {
            document.Info.Title = "HoneyBox API";
            document.Info.Version = "v1";
            document.Info.Description = "抽奖系统API文档 - 提供用户认证、商品管理、订单处理、抽奖系统等功能\n\n" +
                "## 认证说明\n" +
                "大部分接口需要JWT认证，请在请求头中添加：\n" +
                "`Authorization: Bearer <your_token>`\n\n" +
                "## 响应格式\n" +
                "所有接口返回统一格式：\n" +
                "```json\n" +
                "{\n" +
                "  \"status\": 1,  // 1=成功, 0=失败, -1=未登录\n" +
                "  \"msg\": \"success\",\n" +
                "  \"data\": {}\n" +
                "}\n" +
                "```";
            return Task.CompletedTask;
        });
    });


    // 配置 CORS（仅开发环境，生产环境由 Nginx 处理）
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("Development", policy =>
        {
            policy.AllowAnyOrigin()
                  .AllowAnyMethod()
                  .AllowAnyHeader();
        });
    });

    var app = builder.Build();


    // 使用 OpenAPI 和 Scalar UI
    app.MapOpenApi();
    app.MapScalarApiReference(options =>
    {
        options.WithTitle("HoneyBox API");
        options.WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient);
    });

    // 添加根路径重定向到 Scalar 文档
    app.MapGet("/", () => Results.Redirect("/scalar/v1"));
    // 配置 HTTP 请求管道
    if (app.Environment.IsDevelopment())
    {
        // 仅开发环境启用 CORS，生产环境由 Nginx 配置
        app.UseCors("Development");
    }

    // 使用 Serilog 请求日志
    app.UseSerilogRequestLogging();

    // 启用请求体缓冲，允许多次读取
    app.Use(async (context, next) =>
    {
        context.Request.EnableBuffering();
        await next();
    });

    // 使用路由
    app.UseRouting();

    // 使用认证和授权
    app.UseAuthentication();
    app.UseAuthorization();

    // 映射控制器
    app.MapControllers();

    Log.Information("HoneyBox API started successfully");

    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
    Log.CloseAndFlush();
}
