/**
 * Marketplace routes for SentryAgent.ai AgentIdP.
 * All routes are UNAUTHENTICATED — no auth or OPA middleware applied.
 * Guarded by the MARKETPLACE_ENABLED feature flag (defaults to true).
 * When MARKETPLACE_ENABLED=false, all routes return HTTP 404.
 */

import { Router, Request, Response, NextFunction } from 'express';
import { MarketplaceController } from '../controllers/MarketplaceController.js';
import { asyncHandler } from '../utils/asyncHandler.js';

/**
 * Middleware that returns 404 when the MARKETPLACE_ENABLED feature flag is disabled.
 * The flag is considered enabled unless explicitly set to the string "false".
 *
 * @param _req - Express request (unused).
 * @param res - Express response.
 * @param next - Express next function.
 */
function marketplaceFeatureGuard(_req: Request, res: Response, next: NextFunction): void {
  const enabled = process.env['MARKETPLACE_ENABLED'];
  if (enabled === 'false') {
    res.status(404).json({
      code: 'NOT_FOUND',
      message: 'The Agent Marketplace is not enabled on this instance.',
    });
    return;
  }
  next();
}

/**
 * Creates and returns the Express router for public marketplace endpoints.
 *
 * @param marketplaceController - The marketplace controller instance.
 * @returns Configured Express router.
 */
export function createMarketplaceRouter(marketplaceController: MarketplaceController): Router {
  const router = Router();

  // Apply feature flag guard to all marketplace routes
  router.use(marketplaceFeatureGuard);

  // GET /marketplace/agents — list all public agents (unauthenticated, paginated)
  router.get(
    '/agents',
    asyncHandler(marketplaceController.listPublicAgents.bind(marketplaceController)),
  );

  // GET /marketplace/agents/:agentId — get a public agent with DID document (unauthenticated)
  router.get(
    '/agents/:agentId',
    asyncHandler(marketplaceController.getPublicAgent.bind(marketplaceController)),
  );

  return router;
}
