using Microsoft.AspNetCore.Authorization;
using TakeoutSaaS.Module.Authorization.Policies;
namespace TakeoutSaaS.Module.Authorization.Attributes;
/// <summary>
/// 权限校验特性。
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class PermissionAuthorizeAttribute : AuthorizeAttribute
{
    /// <summary>
    /// 初始化权限校验特性并构建对应策略。
    /// </summary>
    /// <param name="permissions">所需的权限标识集合。</param>
    public PermissionAuthorizeAttribute(params string[] permissions)
    {
        // 1. 校验权限参数不为空
        ArgumentNullException.ThrowIfNull(permissions);

        // 2. 规范化权限标识
        var normalized = permissions
            .Where(p => !string.IsNullOrWhiteSpace(p))
            .Select(p => p.Trim())
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .ToArray();

        // 3. 确保至少提供一个有效权限
        if (normalized.Length == 0)
        {
            throw new ArgumentException("至少需要一个权限标识", nameof(permissions));
        }

        // 4. 绑定权限集合并生成策略名称
        Permissions = normalized;
        Policy = PermissionAuthorizationPolicyProvider.BuildPolicyName(normalized);
    }
    /// <summary>
    /// 所需权限集合。
    /// </summary>
    public IReadOnlyCollection<string> Permissions { get; }
}
