const store = {};
async function rateLimit(options) {
  const { key, windowMs, maxRequests } = options;
  const now = Date.now();
  if (Math.random() < 0.01) {
    cleanupExpiredEntries(now);
  }
  const entry = store[key];
  if (!entry || now >= entry.resetTime) {
    store[key] = {
      count: 1,
      resetTime: now + windowMs
    };
    return {
      success: true,
      remaining: maxRequests - 1,
      resetTime: now + windowMs
    };
  }
  if (entry.count >= maxRequests) {
    return {
      success: false,
      remaining: 0,
      resetTime: entry.resetTime,
      retryAfter: Math.ceil((entry.resetTime - now) / 1e3)
      // seconds
    };
  }
  entry.count++;
  return {
    success: true,
    remaining: maxRequests - entry.count,
    resetTime: entry.resetTime
  };
}
function cleanupExpiredEntries(now) {
  Object.keys(store).forEach((key) => {
    if (store[key].resetTime <= now) {
      delete store[key];
    }
  });
}
function resetRateLimit(key) {
  delete store[key];
}
function getRateLimitStatus(key) {
  const entry = store[key];
  const now = Date.now();
  if (!entry || now >= entry.resetTime) {
    return null;
  }
  return {
    success: entry.count < entry.resetTime,
    remaining: Math.max(0, entry.resetTime - entry.count),
    resetTime: entry.resetTime
  };
}
export {
  getRateLimitStatus,
  rateLimit,
  resetRateLimit
};
