using MemberCenter.Application.Abstractions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace MemberCenter.Web.Authorization;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public sealed class AdminPermissionAttribute : TypeFilterAttribute
{
    public AdminPermissionAttribute(string permissionKey)
        : base(typeof(AdminPermissionFilter))
    {
        Arguments = [permissionKey];
    }
}

public sealed class AdminPermissionFilter : IAsyncAuthorizationFilter
{
    private readonly string _permissionKey;
    private readonly IAdminPermissionChecker _permissionChecker;

    public AdminPermissionFilter(string permissionKey, IAdminPermissionChecker permissionChecker)
    {
        _permissionKey = permissionKey;
        _permissionChecker = permissionChecker;
    }

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        var hasPermission = await _permissionChecker.HasPermissionAsync(
            context.HttpContext.User,
            _permissionKey,
            context.HttpContext.RequestAborted);

        if (!hasPermission)
        {
            context.Result = new NotFoundResult();
        }
    }
}
