using System.Reflection;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace JiShe.CollectBus.Host.Swaggers
{
    /// <summary>
    /// 在使用nswag的时候，原生默认的api导致生产的代理类存在问题
    /// 所有隐藏原生的api，重写路由
    /// </summary>
    public class HiddenAbpDefaultApiFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            foreach (ApiDescription apiDescription in context.ApiDescriptions)
            {
                if (apiDescription.TryGetMethodInfo(out MethodInfo _))
                {
                    string key = "/" + apiDescription.RelativePath;
                    if (IsHidden(key))
                        swaggerDoc.Paths.Remove(key);
                }
            }
        }

        private bool IsHidden(string key)
        {
            foreach (string hiddenAbpDefaultApi in GetHiddenAbpDefaultApiList())
            {
                if (key.Contains(hiddenAbpDefaultApi))
                    return true;
            }
            return false;
        }

        private List<string> GetHiddenAbpDefaultApiList()
        {
            return new List<string>()
            {
                "/api/abp/multi-tenancy/tenants",
                "/api/account",
                "/api/feature-management/features",
                "/api/permission-management/permissions",
                "/api/identity/my-profile",
                "/api/identity",
                "/api/multi-tenancy/tenants",
                "/api/setting-management/emailing",
                "/configuration",
                "/outputcache"
            };
        }
    }
}
