interface RateLimitStore {
  [key: string]: { count: number; resetTime: number }
}

const store: RateLimitStore = {}

export interface RateLimitConfig {
  windowMs: number // Time window in milliseconds
  maxRequests: number // Max requests per window
  message?: string
}

export function rateLimit(config: RateLimitConfig) {
  const { windowMs, maxRequests, message = "Too many requests, please try again later" } = config

  return async (identifier: string): Promise<{ allowed: boolean; remaining: number; resetTime: number }> => {
    const now = Date.now()
    const record = store[identifier]

    // Clean up expired entries
    if (record && now > record.resetTime) {
      delete store[identifier]
    }

    // Initialize or get current record
    const current = store[identifier] || { count: 0, resetTime: now + windowMs }

    // Check limit
    if (current.count >= maxRequests) {
      return {
        allowed: false,
        remaining: 0,
        resetTime: current.resetTime,
      }
    }

    // Increment and store
    current.count++
    store[identifier] = current

    return {
      allowed: true,
      remaining: maxRequests - current.count,
      resetTime: current.resetTime,
    }
  }
}

// Predefined rate limiters for common endpoints
export const uploadRateLimit = rateLimit({
  windowMs: 60 * 1000, // 1 minute
  maxRequests: 10,
  message: "Upload limit exceeded. Please wait before uploading again.",
})

export const authRateLimit = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  maxRequests: 5,
  message: "Too many authentication attempts. Please try again later.",
})

export const apiRateLimit = rateLimit({
  windowMs: 60 * 1000, // 1 minute
  maxRequests: 100,
  message: "API rate limit exceeded. Please slow down.",
})

export const streamRateLimit = rateLimit({
  windowMs: 60 * 1000, // 1 minute
  maxRequests: 50,
  message: "Stream rate limit exceeded.",
})
