using Microsoft.AspNetCore.Authorization;
using NetworkResurrector.Api.Application.Services.Abstractions;
using NetworkResurrector.Api.Authorization.Requirements;
using NetworkResurrector.Api.Extensions;
using System.Linq;
using System.Threading.Tasks;

namespace NetworkResurrector.Api.Authorization.Handlers
{
    public class PermissionsBasedAuthorizationHandler : AuthorizationHandler<IPermissionsBasedAuthorizationRequirement>
    {
        private readonly IUserContext _userContext;

        public PermissionsBasedAuthorizationHandler(IUserContext userContext)
        {
            _userContext=userContext;
        }

        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, IPermissionsBasedAuthorizationRequirement requirement)
        {
            var permissions = await _userContext.GetUserPermissions();
            var condition1 = requirement.AllRequired.IsNullOrEmpty() || requirement.AllRequired.All(permission => permissions.Contains(permission));
            var condition2 = requirement.OneOf.IsNullOrEmpty() || requirement.OneOf.Any(permission => permissions.Contains(permission));
            if (condition1 && condition2)
            {
                context.Succeed(requirement);
            }
        }
    }
}
