import rateLimit from 'express-rate-limit';

export const publicSlotsRateLimit = rateLimit({
  windowMs: 60 * 1000,
  max: 60,
  standardHeaders: true,
  legacyHeaders: false,
  message: { error: 'rate_limited', message: 'Too many requests. Please try again later.' },
});

export const publicBookingRateLimit = rateLimit({
  windowMs: 60 * 60 * 1000,
  max: 5,
  keyGenerator: (req) => {
    const email = (req.body as { guestEmail?: string })?.guestEmail ?? req.ip ?? 'unknown';
    return `booking:${email}`;
  },
  standardHeaders: true,
  legacyHeaders: false,
  message: { error: 'rate_limited', message: 'Too many booking attempts. Please try again later.' },
});

/** Unauthenticated host-by-UUID booking (CRM). Higher than public guest limit. */
export const hostByIdBookingRateLimit = rateLimit({
  windowMs: 60 * 60 * 1000,
  max: 60,
  keyGenerator: (req) => {
    const hostId = req.params.userId ?? 'unknown';
    const email = (req.body as { guestEmail?: string })?.guestEmail ?? req.ip ?? 'unknown';
    return `host-booking:${hostId}:${email}`;
  },
  standardHeaders: true,
  legacyHeaders: false,
  message: { error: 'rate_limited', message: 'Too many booking attempts. Please try again later.' },
});

export const authRateLimit = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 20,
  standardHeaders: true,
  legacyHeaders: false,
  message: { error: 'rate_limited', message: 'Too many authentication attempts.' },
});

export const apiRateLimit = rateLimit({
  windowMs: 60 * 1000,
  max: 300,
  standardHeaders: true,
  legacyHeaders: false,
  message: { error: 'rate_limited', message: 'Too many requests.' },
});
