using Microsoft.AspNetCore.Authorization;

namespace ROLAC.API.Authorization;

/// <summary>
/// Gates an action/controller on a configurable permission. Usage:
/// <c>[HasPermission(Modules.Members, PermissionActions.Write)]</c>.
/// Encodes the policy name <c>PERM:&lt;module&gt;:&lt;action&gt;</c>, which
/// <see cref="PermissionPolicyProvider"/> turns into a <see cref="PermissionRequirement"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class HasPermissionAttribute : AuthorizeAttribute
{
    public const string PolicyPrefix = "PERM:";

    public HasPermissionAttribute(string module, string action)
        => Policy = $"{PolicyPrefix}{module}:{action}";

    /// <summary>Parses a policy name back into (module, action), or null if not a PERM policy.</summary>
    public static (string Module, string Action)? Parse(string policyName)
    {
        if (!policyName.StartsWith(PolicyPrefix, StringComparison.Ordinal))
            return null;

        var body  = policyName[PolicyPrefix.Length..];
        var split = body.IndexOf(':');
        if (split <= 0 || split == body.Length - 1)
            return null;

        return (body[..split], body[(split + 1)..]);
    }
}
