using Microsoft.AspNetCore.Authorization;

namespace SIGCM2.Api.Authorization;

/// <summary>
/// Authorization attribute that requires the authenticated user to have at least ONE
/// of the declared permission codes assigned to their role (OR semantics).
/// Implements IAuthorizationRequirementData (.NET 8+) so ASP.NET Core builds the policy
/// on-the-fly from GetRequirements() — no AddPolicy() registration needed.
/// </summary>
/// <example>
/// // Single permission
/// [RequirePermission("administracion:usuarios:gestionar")]
///
/// // Multiple — OR semantics: any single match grants access
/// [RequirePermission("ventas:contado:crear", "ventas:ctacte:crear")]
/// </example>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public sealed class RequirePermissionAttribute
    : AuthorizeAttribute, IAuthorizationRequirement, IAuthorizationRequirementData
{
    /// <summary>Permission codes required (OR semantics — at least one must match).</summary>
    public string[] PermissionCodes { get; }

    public RequirePermissionAttribute(params string[] permissionCodes)
    {
        if (permissionCodes is null || permissionCodes.Length == 0)
            throw new ArgumentException("At least one permission code is required.", nameof(permissionCodes));

        PermissionCodes = permissionCodes;
    }

    /// <inheritdoc/>
    public IEnumerable<IAuthorizationRequirement> GetRequirements() => new[] { this };
}
