import type { NextFunction, Request, Response } from 'express';

type Bucket = {
  count: number;
  windowStart: number;
};

const buckets = new Map<string, Bucket>();

export const rateLimit = (options: { keyPrefix: string; windowMs: number; max: number }) => {
  return (req: Request, res: Response, next: NextFunction): void => {
    const key = `${options.keyPrefix}:${req.ip ?? 'unknown'}`;
    const now = Date.now();
    const current = buckets.get(key);

    if (!current || now - current.windowStart > options.windowMs) {
      buckets.set(key, { count: 1, windowStart: now });
      next();
      return;
    }

    if (current.count >= options.max) {
      res.status(429).json({ message: 'Rate limit exceeded. Try again later.' });
      return;
    }

    current.count += 1;
    buckets.set(key, current);
    next();
  };
};
