using Core.Enumerations;
using DataProviders.Collections;
using DomainObjects.Documents;
using DomainObjects.Enumerations;
using Microsoft.AspNetCore.Authorization;
using WeatherForecast.Policies.Abstractions;
using WeatherForecast.Services;

namespace WeatherForecast.Policies {
  public class ShopAuthorizationHandler : AuthorizationHandlerBase<ShopAuthorizationRequirement, List<ShopDocument>> {

    public ShopAuthorizationHandler(
      IHttpContextAccessor contextAccessor,
      IUserDataProvider userDataProvider,
      IAccountPolicyService accountService
    ) : base(contextAccessor, userDataProvider, accountService) { }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ShopAuthorizationRequirement requirement, List<ShopDocument> resource) {
      var user = GetUser(context);
      if (user == null)
        return Task.CompletedTask;

      // Can Admin, Shop manager
      if (requirement.Action == CrudActions.Create
        && user.Role != Roles.Admin
        && user.Role != Roles.ShopManager)
        return Task.CompletedTask;

      // Can Admin, Shop manager
      if (requirement.Action == CrudActions.Read
        && user.Role != Roles.Admin
        && user.Role != Roles.ShopManager)
        return Task.CompletedTask;

      // Can Admin, Shop manager
      if (requirement.Action == CrudActions.Update
        && user.Role != Roles.Admin
        && user.Role != Roles.ShopManager)
        return Task.CompletedTask;

      // Can Admin, Shop manager
      if (requirement.Action == CrudActions.Delete
        && user.Role != Roles.Admin
        && user.Role != Roles.ShopManager)
        return Task.CompletedTask;


      context.Succeed(requirement);

      return Task.CompletedTask;
    }
  }

  /// <summary>
  /// 
  /// </summary>
  public class ShopAuthorizationRequirement : AuthorizationRequirementBase { }
}
