import rateLimit from "express-rate-limit"
import * as Sentry from "@sentry/node"
import { AuthorizedUserReq } from "../types.js"
import { isCodeflashEmployee } from "../utils/employee-utils.js"

// Load values from environment or use defaults
const RATE_LIMIT_WINDOW_MS = parseInt(process.env.RATE_LIMIT_WINDOW_MS || "60000", 10)
const RATE_LIMIT_MAX = parseInt(process.env.RATE_LIMIT_MAX || "30", 10)

// Common configuration for rate limiters
const baseRateLimitConfig = {
  windowMs: RATE_LIMIT_WINDOW_MS, // in milliseconds
  max: RATE_LIMIT_MAX,
  standardHeaders: true,
  legacyHeaders: false,
  handler: (req, res, next, options) => {
    // Log rate limit hit to Sentry
    Sentry.captureMessage("Rate limit exceeded", {
      level: "warning",
      extra: {
        ip: req.ip,
        path: req.path,
        method: req.method,
        limiterType: "id",
      },
    })

    // Send standard rate limit response
    res.status(options.statusCode).send(options.message)
  },
}

// ID-based rate limiter
export const idLimiter = rateLimit({
  ...baseRateLimitConfig,
  skip: (req: AuthorizedUserReq) => {
    // Skip if no userId is set — typically means checkForValidAPIKey hasn't run yet
    if (!req.userId) return true

    if (isCodeflashEmployee(req.userId)) return true

    return false
  },
  keyGenerator: (req: AuthorizedUserReq) => `ratelimit:user:${req.userId}:${req.path}`,
})
