/**
 * Rate limiting utility
 * Simple in-memory rate limiter for API routes
 */

interface RateLimitRecord {
  count: number
  resetTime: number
}

interface RateLimitStore {
  [key: string]: RateLimitRecord
}

const store: RateLimitStore = {}

// Cleanup old entries every 5 minutes
setInterval(() => {
  const now = Date.now()
  Object.keys(store).forEach((key) => {
    if (store[key].resetTime < now) {
      delete store[key]
    }
  })
}, 5 * 60 * 1000)

export interface RateLimitResult {
  allowed: boolean
  remaining: number
  resetTime: number
}

export class RateLimit {
  private limit: number
  private windowMs: number

  /**
   * Create a new rate limiter
   * @param limit - Maximum number of requests allowed in the window
   * @param windowMs - Time window in milliseconds (default: 60000 = 1 minute)
   */
  constructor(limit: number = 10, windowMs: number = 60000) {
    this.limit = limit
    this.windowMs = windowMs
  }

  /**
   * Check if a request is allowed
   * @param identifier - Unique identifier (e.g., IP address, user ID)
   * @returns Rate limit result with allowed status and remaining count
   */
  check(identifier: string): RateLimitResult {
    const now = Date.now()
    const record = store[identifier]

    // No record or expired window - allow and create new record
    if (!record || now > record.resetTime) {
      store[identifier] = {
        count: 1,
        resetTime: now + this.windowMs,
      }
      return {
        allowed: true,
        remaining: this.limit - 1,
        resetTime: now + this.windowMs,
      }
    }

    // Limit exceeded
    if (record.count >= this.limit) {
      return {
        allowed: false,
        remaining: 0,
        resetTime: record.resetTime,
      }
    }

    // Increment and allow
    record.count++
    return {
      allowed: true,
      remaining: this.limit - record.count,
      resetTime: record.resetTime,
    }
  }

  /**
   * Reset rate limit for a specific identifier
   * @param identifier - Unique identifier to reset
   */
  static reset(identifier: string): void {
    delete store[identifier]
  }

  /**
   * Clear all rate limit records
   */
  static clearAll(): void {
    Object.keys(store).forEach((key) => delete store[key])
  }
}

/**
 * Get client IP address from request
 * @param request - Next.js request object
 * @returns Client IP address
 */
export function getClientIp(request: Request): string {
  // Try x-forwarded-for first (for proxies/load balancers)
  const forwarded = request.headers.get("x-forwarded-for")
  if (forwarded) {
    return forwarded.split(",")[0].trim()
  }

  // Try x-real-ip
  const realIp = request.headers.get("x-real-ip")
  if (realIp) {
    return realIp
  }

  // Fallback to a generic identifier
  return "unknown"
}






