using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Text;

namespace IRaCIS.Core.Application.BusinessFilter;

/// <summary>
/// 测试加密API 返回的结果
/// </summary>
public class EncreptApiResultFilter : IAsyncResultFilter
{
    private readonly IOptionsMonitor<IRCEncreptOption> _encreptResponseMonitor;

    public EncreptApiResultFilter(IOptionsMonitor<IRCEncreptOption> encreptResponseMonitor)
    {
        _encreptResponseMonitor = encreptResponseMonitor;
    }

    public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {

        if (_encreptResponseMonitor.CurrentValue.IsResponseEncreptEnable)
        {

            if (context.Result is ObjectResult objectResult)
            {
                var statusCode = objectResult.StatusCode ?? context.HttpContext.Response.StatusCode;

                var objectValue = objectResult.Value;


                if (objectValue is IResponseOutput)
                {
                    var responseOutput = objectValue as IResponseOutput<object>;

                    var path = context.HttpContext?.Request.Path.Value?.ToLower();


                    if (!string.IsNullOrEmpty(path) && path.Length > 5 && _encreptResponseMonitor.CurrentValue.ApiPathList.Contains(path.ToLower()))
                    {

                        if (responseOutput.IsSuccess)
                        {
                            responseOutput.Code = ApiResponseCodeEnum.ResultEncrepted;
                            responseOutput.Data = JsonConvert.SerializeObject(Convert.ToBase64String(Encoding.UTF8.GetBytes(responseOutput.Data.ToString())));

                            objectResult.Value = responseOutput;
                        }

                    }

                }
            }
        }
        await next.Invoke();
    }
}
