using Fuel.Core;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFS.Core.Mvc.Middlewares
{
    public class SignatureValidationMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly SignatureValidator _validator;

        public SignatureValidationMiddleware(RequestDelegate next, SignatureValidator validator)
        {
            _next = next;
            _validator = validator;
        }

        /// <summary>
        /// 处理每个 HTTP 请求的异步方法。
        /// </summary>
        /// <param name="context">HTTP 上下文。</param>
        /// <returns>一个任务表示的操作。</returns>
        public async Task InvokeAsync(HttpContext context, Authorization _authorization)
        {
            // 跳过登录接口
            var path = context.Request.Path.Value;
            if (path.StartsWith("/api/Auth/login", StringComparison.OrdinalIgnoreCase))
            {
                await _next(context);
                return;
            }
            var headers = context.Request.Headers;
            var authorization = headers["authorization"];
            if (string.IsNullOrEmpty(authorization))
            {
            }
            var Bread = authorization.ToString().Split(' ');
            if (Bread.Count() == 2)
            {
                // 验证token
                {
                    var token = Bread[1];
                    bool isValid = JwtValidator.ValidateToken(token);
                    if (!isValid)
                    {
                        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        await context.Response.WriteAsync("token验证失败");
                        return;
                    }
                }

                //子站接入验证签名
                //{
                //    if (Bread[0] == "Bread")
                //    {
                //        if (!_validator.ValidateSignature(context.Request))
                //        {
                //            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                //            await context.Response.WriteAsync("无效的签名");
                //            return;
                //        }
                //    }
                //}
               
            }
            else
            {
                var SecretId = headers["secret_id"];
                if (string.IsNullOrEmpty(authorization))
                {
                }
                var apply = _authorization.GetApply(SecretId);
                if (apply == null)
                {
                    context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    await context.Response.WriteAsync("无效的签名，未找到SecretId");
                    return;
                }
                var ValidateSignature = await _validator.ValidateSignature(context.Request, apply.AppSecret);
                if (ValidateSignature)
                {
                    await _next(context);
                    return;
                }
                //await _next(context);
                //return;

                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                await context.Response.WriteAsync("无效的签名");
                return;
            }
          

            await _next(context);
        }
    }
}

