using Microsoft.AspNetCore.Authorization;

using DomainObjects.Documents;
using Core.Enumerations;

using DataProviders.Collections;

using WeatherForecast.Policies.Abstractions;
using WeatherForecast.Services;
using DomainObjects.Enumerations;

namespace WeatherForecast.Policies;

/// <summary>
/// 
/// </summary>
public class BlogAuthorizationHandler : AuthorizationHandlerBase<BlogAuthorizationRequirement, List<BlogDocument>> {

  /// <summary>
  /// 
  /// </summary>
  /// <param name="contextAccessor"></param>
  /// <param name="userDataProvider"></param>
  /// <param name="accountService"></param>
  public BlogAuthorizationHandler(
    IHttpContextAccessor contextAccessor,
    IUserDataProvider userDataProvider,
    IAccountPolicyService accountService
  ) : base(contextAccessor, userDataProvider, accountService) { }

  /// <summary>
  /// 
  /// </summary>
  /// <param name="context"></param>
  /// <param name="requirement"></param>
  /// <param name="resource"></param>
  /// <returns></returns>
  protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, BlogAuthorizationRequirement requirement, List<BlogDocument> resource) {

    var user = GetUser(context);
    if (user == null)
      return Task.CompletedTask;

    // Can only Admin, Editor, Author, Contributor (cannot set publish date)
    if (requirement.Action == CrudActions.Create
      && (user.Role != Roles.Admin
      && user.Role != Roles.Editor
      && user.Role != Roles.Author
      && user.Role != Roles.Contributor
      && (user.Role == Roles.Contributor && resource.Any(x => x.Published != null))))
      return Task.CompletedTask;

    // Can only Admin, Editor, Author, Contributor
    if (requirement.Action == CrudActions.Read
      && (user.Role != Roles.Admin
      && user.Role != Roles.Editor
      && user.Role != Roles.Author
      && user.Role != Roles.Contributor))
      return Task.CompletedTask;

    // Can only Admin, Editor, Author (own), Contributor (own, not yet pubblished)
    if ((requirement.Action == CrudActions.Update || requirement.Action == CrudActions.Delete)
      && (user.Role != Roles.Admin
      && user.Role != Roles.Editor
      && user.Role != Roles.Author
      && user.Role != Roles.Contributor
      && ((user.Role == Roles.Author || user.Role == Roles.Contributor) && resource.Any(x => x.Author != user.Id))
      && (user.Role == Roles.Contributor && resource.Any(x => x.Published != null))))
      return Task.CompletedTask;

    context.Succeed(requirement);

    return Task.CompletedTask;
  }
}

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

