using Microsoft.AspNetCore.Http;
using System.Net;
using System.Threading.Tasks;
using System;

namespace MS.WebApi.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)
        {
            // 跳过登录接口
            var path = context.Request.Path.Value;
            if (!path.StartsWith("/api/Account/SendSMS", StringComparison.OrdinalIgnoreCase))
            {
                await _next(context);
                return;
            }
            var headers = context.Request.Headers;

            //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, "tWWGfad0WMZxQy7i5ZNz64HB678JiYC2");
            if (ValidateSignature)
            {
                await _next(context);
                return;
            }
            //await _next(context);
            //return;

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


            await _next(context);
        }
    }
    public class AdApply
    { 
         public string AppSecret { get; set; }
    }
}
