

using DFS.Core.Mvc;
using DFS.Infrastructure.Redis.Extension;
using FreeSql;
using Fuel.Application;
using Fuel.Application.Repositories;
using Fuel.Application.Service;
using Fuel.Infrastructure;
using Fuel.Payment.Service.AliPaymentProcessor.Alipay;
using Fuel.Payment.Service.AllInPayProcessor.AllInPay;
using Fuel.Payment.Service.Factory;
using Fuel.Payment.Service.Pay;
using Fuel.Payment.Service.UnionPayProcessor;
using Fuel.PaymentServer.MicServer;
using Fuel.Infrastructure.Extension;
using CSRedis;
using Microsoft.Extensions.Logging;
using Fuel.Core;
using Microsoft.AspNetCore.Authorization;
using Fuel.Application.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using DFS.Core.Mvc.Middlewares;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IPayService, PayService>();
AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "ALI_SCAN", new AlipayPaymentProcessor());
//AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "WX_SCAN", new WechatPaymentProcessor());
AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "ALL_IN_SCAN", new AllInPayProcessor());
//AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "ALL_IN_SCAN_V2", new AllInPayProcessorV2());
//AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "WX_ORDER_SCAN", new WechatPaymentProcessor());
AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "ALI_ORDER_SCAN", new AlipayPaymentProcessor());
//AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "WECHAT_MINIPROGRAM_PAY", new WechatPaymentProcessor());
//AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "ICBC_SCAN", new IcbcPayProcessor());
//AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "ICBC_ORDER_SCAN", new IcbcPayProcessor());
//AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "GRG_SCAN", new GrgPayProcessor());
AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "UNION_MINI", new MiniUnionPayProcessor());
AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "UNION_SCAN", new UnionPayProcessor());
// Add services to the container.
// 添加FreeSQL配置
builder.Services.AddFreeSql(builder.Configuration);

//初始化DFS Server
builder.Services.AddMicService(builder.Environment);
//builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
//    .AddJwtBearer(options =>
//    {
//        options.TokenValidationParameters = new TokenValidationParameters
//        {
//            ValidateIssuer = true,
//            ValidateAudience = true,
//            ValidateLifetime = true,
//            ValidateIssuerSigningKey = true,
//            ValidIssuer = ConstKey.JwtIssuer,
//            ValidAudience = ConstKey.JwtAudience,
//            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConstKey.JwtKey))
//        };
//    });

builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<INozzleRepository, NozzleRepository>();
builder.Services.AddScoped<INozzleService, NozzleService>();
builder.Services.AddScoped<ITransactionsService, TransactionsService>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IApplyService, ApplyService>();
builder.Services.AddScoped<Authorization>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddTransient<IAuthorizationHandler, PermissionHandler>();

Fuel.Infrastructure.Extension.RedisOptions redisOptions = builder.Configuration.GetSection("Redis").Get<Fuel.Infrastructure.Extension.RedisOptions>();
builder.Services.UseRedisClient(redisOptions);
// 动态添加基于权限的策略
void AddPermissionPolicies(AuthorizationOptions options)
{
    //var permissions = Authorization.GetPermissions();

    //foreach (var permission in permissions)
    //{
    //    options.AddPolicy($"Permission_{permission}", policy =>
    //        policy.Requirements.Add(new PermissionRequirement(permission)));
    //}
    using (var scope = builder.Services.BuildServiceProvider().CreateScope())
    {
        var userService = scope.ServiceProvider.GetRequiredService<IUserService>();
        var applyService = scope.ServiceProvider.GetRequiredService<IApplyService>();
        var authorization = new Authorization(userService, applyService);
        var permissions = authorization.GetPermissions();

        foreach (var permission in permissions)
        {
            options.AddPolicy($"Permission_{permission}", policy =>
                policy.Requirements.Add(new PermissionRequirement(permission)));
        }
    }
}

builder.Services.AddAuthorization(options =>
{
    AddPermissionPolicies(options);
});

var app = builder.Build();

app.UseRouting();

var loggerFactory = LoggerFactory.Create(builder =>
{
    builder.AddConsole();
});
var logger = loggerFactory.CreateLogger<DFS.Core.Mvc.Middlewares.SignatureValidator>();
var signatureValidator = new DFS.Core.Mvc.Middlewares.SignatureValidator(logger);
app.UseMiddleware<SignatureValidationMiddleware>(signatureValidator);//签名验证

// 配置HttpRequestReader静态类
var httpContextAccessor = app.Services.GetRequiredService<IHttpContextAccessor>();
HttpRequestReader.Configure(httpContextAccessor);

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

app.UseDFSServer();

app.UseHttpsRedirection();

app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();
app.Urls.Add("http://192.168.0.202:5006");
app.Run();
