/**
 * Native Cloudflare rate-limit middleware — system-communications-notifications.
 *
 * Application points (wired by the consuming spec):
 *   1. Auth login      — `rateLimit(env.RATE_LIMITER_AUTH, ip)`   (foundation-auth-rbac)
 *   2. Auth signup     — `rateLimit(env.RATE_LIMITER_AUTH, ip)`   (foundation-auth-rbac)
 *   3. Password reset  — `rateLimit(env.RATE_LIMITER_AUTH, ip)`   (foundation-auth-rbac)
 *   4. Inbound webhooks— `rateLimit(env.RATE_LIMITER_WEBHOOK, ip)` (this spec, Task 14)
 *
 * The `binding` argument is the Cloudflare native RateLimit binding declared in
 * wrangler.toml under [[unsafe.bindings]] type = "ratelimit". The `key` is
 * the per-request discriminator (typically the client IP from CF-Connecting-IP).
 */
import type { Context, Next } from 'hono'

/** RateLimit binding shape exposed by Cloudflare Workers. */
interface RateLimit {
  limit(options: { key: string }): Promise<{ success: boolean }>
}

/**
 * Returns a Hono middleware that enforces the given rate-limit binding.
 * Short-circuits with 429 when `binding.limit` returns `{ success: false }`.
 */
export function rateLimit(binding: RateLimit | undefined | null, key: string) {
  return async (c: Context, next: Next) => {
    if (binding) {
      try {
        const { success } = await binding.limit({ key })
        if (!success) return c.json({ error: 'Too many requests' }, 429)
      } catch {
        // binding unavailable — degrade gracefully
      }
    }
    await next()
  }
}
