import { Router, Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
import { redis } from '../../config/redis';
import { env } from '../../config/env';
import { search } from './search.service';

const router = Router();

const searchRateLimit = rateLimit({
  windowMs: 60 * 1000,
  max: 20,
  standardHeaders: true,
  legacyHeaders: false,
  store: new RedisStore({
    sendCommand: (command: string, ...args: string[]) => redis.call(command, ...args) as Promise<any>,
    prefix: 'rl:search:',
  }),
  message: { error: { message: 'Too many search requests, please slow down', code: 'SEARCH_RATE_LIMIT_EXCEEDED' } },
});

// GET /api/search?q=<query>&limit=5
router.get('/', searchRateLimit, async (req: Request, res: Response, next: NextFunction) => {
  try {
    const q = (req.query.q as string || '').trim();
    const limit = Math.min(parseInt(req.query.limit as string) || 5, 20);
    if (!q || q.length < 2) {
      res.json([]);
      return;
    }
    // Lightweight auth check — shifts only returned for authenticated users
    let isAuthenticated = false;
    const authHeader = req.headers.authorization;
    if (authHeader?.startsWith('Bearer ')) {
      try {
        jwt.verify(authHeader.slice(7), env.JWT_ACCESS_SECRET, { algorithms: ['HS256'] });
        isAuthenticated = true;
      } catch { /* unauthenticated — public results only */ }
    }
    const results = await search(q, limit, isAuthenticated);
    res.json(results);
  } catch (err) {
    next(err);
  }
});

export { router as searchRouter };
