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

namespace WeatherForecast.Policies;

/// <summary>
/// 
/// </summary>
public class PasswordChangeAuthorizationHandler : AuthorizationHandlerBase<PasswordChangeRequirement, List<UserDocument>> {

  /// <summary>
  /// 
  /// </summary>
  /// <param name="contextAccessor"></param>
  /// <param name="userDataProvider"></param>
  /// <param name="accountService"></param>
  public PasswordChangeAuthorizationHandler(
    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, PasswordChangeRequirement requirement, List<UserDocument> resource) {

    // User from token
    var user = GetUser(context);
    if (user == null)
      return Task.CompletedTask;

    if(user.Role != Roles.Admin && resource.Any(x => x.Id != user.Id))
      return Task.CompletedTask;

    if (resource.Count() > 0 && resource.Any(x => x.Id == user.Id))
      return Task.CompletedTask;

    if (resource.All(x => x.Id == user.Id)) {

      if (user.Passwords.Password == null)
        return Task.CompletedTask;

      if (!HashService.ValidateHash(requirement.OldPassword, user.Passwords.Password.Salt, user.Passwords.Password.Hash))
        return Task.CompletedTask;
    }
    



    context.Succeed(requirement);

    return Task.CompletedTask;
  }

}
public class PasswordChangeRequirement : AuthorizationRequirementBase {
  public string OldPassword { get; init; }
}



