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

const BOT_PATTERNS = [
  /googlebot/i,
  /bingbot/i,
  /yandexbot/i,
  /baiduspider/i,
  /scrapy/i,
  /curl\//i,
  /wget\//i,
  /python-requests/i,
  /python-urllib/i,
  /httpx/i,
  /aiohttp/i,
  /headlesschrome/i,
  /selenium/i,
  /phantomjs/i,
  /puppeteer/i,
  /playwright/i,
  /httrack/i,
  /go-http-client/i,
  /java\//i,
  /libwww-perl/i,
];

const PUBLIC_FORECAST_GET_ALLOWLIST = new Set([
  '/top-props',
  '/top-picks',
]);

export function blockBots(req: Request, res: Response, next: NextFunction) {
  const authHeader = req.headers.authorization;
  if (authHeader && authHeader.startsWith('Bearer ')) {
    next();
    return;
  }

  if (req.method === 'GET' && PUBLIC_FORECAST_GET_ALLOWLIST.has(req.path)) {
    next();
    return;
  }

  const ua = req.headers['user-agent'] || '';

  // Reject empty user-agent
  if (!ua) {
    return res.status(403).json({ error: 'Forbidden' });
  }

  // Check against known bot patterns
  for (const pattern of BOT_PATTERNS) {
    if (pattern.test(ua)) {
      return res.status(403).json({ error: 'Forbidden' });
    }
  }

  next();
}
