/**
 * Rate Limiter for admin functions
 */

import { RateLimiter } from './security'

const rateLimiter = new RateLimiter()

export interface RateLimitConfig {
  maxRequests: number
  windowMs: number
}

export const RATE_LIMITS: Record<string, RateLimitConfig> = {
  pause: { maxRequests: 5, windowMs: 60000 }, // 5 per minute
  unpause: { maxRequests: 5, windowMs: 60000 },
  setAdmin: { maxRequests: 1, windowMs: 3600000 }, // 1 per hour
  anchorStateProof: { maxRequests: 10, windowMs: 60000 }, // 10 per minute
  mirrorTransaction: { maxRequests: 20, windowMs: 60000 }, // 20 per minute
  default: { maxRequests: 10, windowMs: 60000 },
}

export function checkRateLimit(
  identifier: string,
  actionOrMaxRequests: string | number = 'default',
  windowMs?: number
): { allowed: boolean; remaining?: number; resetAt?: number } {
  const config =
    typeof actionOrMaxRequests === 'number'
      ? { maxRequests: actionOrMaxRequests, windowMs: windowMs ?? RATE_LIMITS.default.windowMs }
      : RATE_LIMITS[actionOrMaxRequests] || RATE_LIMITS.default
  const allowed = rateLimiter.checkLimit(identifier, config.maxRequests)

  if (!allowed) {
    const resetAt = Date.now() + config.windowMs
    return { allowed: false, remaining: 0, resetAt }
  }

  return { allowed: true }
}

export function clearRateLimit(identifier?: string): void {
  rateLimiter.clear(identifier)
}
