using Microsoft.AspNetCore.Mvc.Filters;
using OmsorgCore.Application.Abstractions;
using OmsorgCore.Domain.Enums;

namespace OmsorgCore.Api.Security;

/// <summary>
/// Erzwingt die Rechteprüfung auf Endpunkt-Ebene serverseitig, zusätzlich zur Prüfung auf
/// Datenebene in den Application-Services (REQUIREMENTS.md NFR-9).
/// Verwendung: [RequirePermission(ModuleType.Employees, PermissionAction.Create)]
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class RequirePermissionAttribute : Attribute, IAsyncAuthorizationFilter
{
    private readonly ModuleType _module;
    private readonly PermissionAction _action;

    public RequirePermissionAttribute(ModuleType module, PermissionAction action)
    {
        _module = module;
        _action = action;
    }

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        var currentUser = context.HttpContext.RequestServices.GetRequiredService<ICurrentUserService>();
        if (!currentUser.IsAuthenticated || currentUser.UserId is null)
        {
            context.Result = new Microsoft.AspNetCore.Mvc.UnauthorizedResult();
            return;
        }

        var permissionService = context.HttpContext.RequestServices.GetRequiredService<IPermissionService>();
        var allowed = await permissionService.HasPermissionAsync(currentUser.UserId.Value, _module, _action);

        if (!allowed)
        {
            context.Result = new Microsoft.AspNetCore.Mvc.ForbidResult();
        }
    }
}
