namespace OpenWaf.Domain.Security;
///
/// A request budget written for one path rather than for the whole edge (OPEN-68).
///
/// The edge-wide budget (OPEN-56) is one number for the whole site, and for a
/// login path that number is always wrong: 100 requests a minute does not stop a
/// credential-stuffing run that makes twenty attempts a minute — twenty looks
/// like a person — while 5 a minute locks an honest office behind one NAT out of
/// every page they own. The only way to make both statements true is to price
/// the paths differently, which is what this row does: a glob over the request
/// path, its own limit, its own window.
///
/// What it is not:
/// * It is not a path rule (). A path rule refuses a
/// request because of what it asked for; a rate rule refuses it because of how
/// often that source asked. The pattern language is shared because the thing
/// being described — "this path and what hangs off it" — is the same.
/// * It is not a ban. Crossing a path budget pauses that source on that path
/// for the rest of that window and nothing more. The claim is about one path,
/// and writing an engine ban for it would refuse the visitor the rest of the
/// site as punishment for a login-page rate.
///
public sealed class RateRule
{
public long Id { get; init; }
/// The budget a rule gets when the request names none. The same
/// numbers the edge-wide pillar ships with, so a rule written without
/// numbers behaves like the pillar the operator already has.
public const int DefaultLimitPerWindow = 20;
/// And its window, for the same reason.
public const int DefaultWindowSeconds = 60;
/// Glob over the request path — the same
/// matcher as a path rule: anchored,
/// case-insensitive, * and ? only, never a regular expression.
public string Pattern { get; set; } = string.Empty;
/// How many requests one source may make to the matched paths inside
/// . The request that crosses it is the breach.
public int LimitPerWindow { get; set; } = DefaultLimitPerWindow;
/// How long that budget lasts, per source: the window starts when
/// that source first asks, exactly as the edge-wide window does.
public int WindowSeconds { get; set; } = DefaultWindowSeconds;
public string? Note { get; set; }
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
/// A budget written for an incident stops being true when the
/// incident ends. Same rule as a path rule's expiry.
public DateTimeOffset? ExpiresAt { get; set; }
public bool IsLive(DateTimeOffset now) => ExpiresAt is null || ExpiresAt > now;
/// The window as a span, with the same floor the edge-wide budget
/// uses: a zero or negative window is not "no wait", it is a counter that
/// resets between the check and the answer.
public TimeSpan Window => WindowSeconds > 0 ? TimeSpan.FromSeconds(WindowSeconds) : TimeSpan.FromSeconds(1);
}