using Netmash.Extensions.Caching.Services;
using Netmash.Security.Authentication.Tuitio.Abstractions;
using NetworkResurrector.Api.Application.Services.Abstractions;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace NetworkResurrector.Api.Application.Services.Decorators
{
    internal class UserContextCache : IUserContext
    {
        private readonly IUserContextAccessor _userContextAccessor;
        private readonly IUserContext _inner;
        private readonly ICacheService _cache;

        public UserContextCache(IUserContextAccessor userContextAccessor, IUserContext inner, ICacheService cache)
        {
            _userContextAccessor=userContextAccessor;
            _inner=inner;
            _cache=cache;
        }

        public async Task<IEnumerable<string>> GetUserPermissions()
        {
            var key = $"UserPermissions_{_userContextAccessor.UserId}";
            var result = await _cache.GetAsync<IEnumerable<string>>(key);
            if (result == null)
            {
                result = await _inner.GetUserPermissions();
                await _cache.SetAsync(key, result);
            }
            return result;
        }
    }
}
