import rateLimit from 'express-rate-limit';
import type { RequestHandler } from 'express';
import { isProductionSecurityMode, loadCustomerSecurityPolicy, resolveOmnlPrincipal } from '@dbis/integration-foundation';

function asHandler(h: ReturnType<typeof rateLimit>): RequestHandler {
  return h as unknown as RequestHandler;
}

export const settlementRateLimiter = asHandler(
  rateLimit({
    windowMs: 60_000,
    max: (req) => {
      if (!isProductionSecurityMode()) return 200;
      const policy = loadCustomerSecurityPolicy();
      const principal = resolveOmnlPrincipal(req);
      if (!principal) return policy.rateLimits.anonymousPerMinute;
      if (principal.role === 'customer') return policy.rateLimits.customerPerMinute;
      return policy.rateLimits.superAdminPerMinute;
    },
    message: { error: 'Too many requests — rate limit exceeded' },
    standardHeaders: true,
    legacyHeaders: false,
  }),
);
