using Hotline.Caching.Interfaces;
using Hotline.Settings;
using XF.Domain.Cache;
using XF.Domain.Dependency;

namespace Hotline.Caching.Services
{
    public class RolePermissionsCacheManager : IRolePermissionsCacheManager, IScopeDependency
    {
        private const string RolePermissionCacheKey = "RolePermissionCache:";
        private readonly ITypedCache<IReadOnlyList<string>> _cache;
        private readonly ISystemAuthorityRepository _systemAuthorityRepository;

        public RolePermissionsCacheManager(ITypedCache<IReadOnlyList<string>> cache, ISystemAuthorityRepository systemAuthorityRepository)
        {
            _cache = cache;
            _systemAuthorityRepository = systemAuthorityRepository;
        }

        public IReadOnlyList<string> GetPermissions(string role)
        {
            return _cache.GetOrSet(GetKey(role), d =>
                {
                    //todo 加上全局配置,对未开启模块过滤
                    var systemAuth = _systemAuthorityRepository.GetAsync(d => d.RoleCode == role).GetAwaiter()
                        .GetResult();
                    return systemAuth?.GetPermissions() ?? new();
                }
            ) ?? new List<string>();
        }

        public void RemovePermissions(string role)
        {
            _cache.Remove(GetKey(role));
        }


        private string GetKey(string role) =>
            $"{RolePermissionCacheKey}{role}";
    }
}
