import type { Env } from '../env';

export class RateLimitError extends Error {
  code = 'RATE_LIMITED';
  status = 429;
}

export async function enforceRateLimit(
  env: Env['Bindings'],
  key: string,
  limit: number,
  windowSeconds: number
): Promise<{ count: number; remaining: number }> {
  const now = Math.floor(Date.now() / 1000);
  const bucket = Math.floor(now / windowSeconds);
  const kvKey = `ratelimit:${key}:${bucket}`;
  const current = Number((await env.KV.get(kvKey)) || '0') + 1;
  await env.KV.put(kvKey, String(current), { expirationTtl: windowSeconds + 30 });
  if (current > limit) throw new RateLimitError('操作太频繁，请稍后再试');
  return { count: current, remaining: Math.max(0, limit - current) };
}
