/**
 * OAuth 2.0 Token routes for SentryAgent.ai AgentIdP.
 * POST /token uses no Bearer auth (credentials are in the body).
 * POST /token/introspect and POST /token/revoke require Bearer auth and OPA authorization.
 */

import { Router, RequestHandler } from 'express';
import { TokenController } from '../controllers/TokenController.js';
import { authMiddleware } from '../middleware/auth.js';
import { rateLimitMiddleware } from '../middleware/rateLimit.js';
import { asyncHandler } from '../utils/asyncHandler.js';

/**
 * Creates and returns the Express router for token endpoints.
 *
 * @param tokenController - The token controller instance.
 * @param opaMiddleware - The OPA authorization middleware created at startup.
 * @returns Configured Express router.
 */
export function createTokenRouter(tokenController: TokenController, opaMiddleware: RequestHandler): Router {
  const router = Router();

  // POST /token — Issue token (no auth — credentials in body or Basic header)
  router.post('/', asyncHandler(rateLimitMiddleware), asyncHandler(tokenController.issueToken.bind(tokenController)));

  // POST /token/introspect — Introspect token (requires Bearer auth + OPA)
  router.post(
    '/introspect',
    asyncHandler(authMiddleware),
    opaMiddleware,
    asyncHandler(rateLimitMiddleware),
    asyncHandler(tokenController.introspectToken.bind(tokenController)),
  );

  // POST /token/revoke — Revoke token (requires Bearer auth + OPA)
  router.post(
    '/revoke',
    asyncHandler(authMiddleware),
    opaMiddleware,
    asyncHandler(rateLimitMiddleware),
    asyncHandler(tokenController.revokeToken.bind(tokenController)),
  );

  return router;
}
