/**
 * Scaffold routes for SentryAgent.ai AgentIdP.
 * Provides the GET /sdk/scaffold/:agentId endpoint.
 */

import { Router, RequestHandler, Request, Response, NextFunction } from 'express';
import { RateLimiterMemory } from 'rate-limiter-flexible';
import { ScaffoldController } from '../controllers/ScaffoldController.js';
import { asyncHandler } from '../utils/asyncHandler.js';
import { RateLimitError } from '../utils/errors.js';

/** Scaffold-specific rate limiter: 10 requests per minute per tenant. */
const scaffoldRateLimiter = new RateLimiterMemory({ points: 10, duration: 60 });

/**
 * Express middleware enforcing the scaffold-specific rate limit by tenant ID.
 */
async function scaffoldRateLimitMiddleware(
  req: Request,
  res: Response,
  next: NextFunction,
): Promise<void> {
  const tenantId = req.user?.organization_id ?? req.ip ?? 'unknown';
  try {
    await scaffoldRateLimiter.consume(tenantId);
    next();
  } catch {
    const retryAfter = Math.ceil(60);
    res.setHeader('Retry-After', String(retryAfter));
    next(new RateLimitError());
  }
}

/**
 * Creates and returns the Express router for scaffold endpoints.
 *
 * Routes:
 *   GET /sdk/scaffold/:agentId — authenticated; generate and stream a scaffold ZIP
 *
 * @param controller - The scaffold controller instance.
 * @param authMiddleware - The JWT authentication middleware.
 * @returns Configured Express router.
 */
export function createScaffoldRouter(
  controller: ScaffoldController,
  authMiddleware: RequestHandler,
): Router {
  const router = Router();

  router.get(
    '/sdk/scaffold/:agentId',
    authMiddleware,
    asyncHandler(scaffoldRateLimitMiddleware),
    asyncHandler(controller.getScaffold.bind(controller)),
  );

  return router;
}
