/**
 * Credential Management routes for SentryAgent.ai AgentIdP.
 * All routes are under /agents/:agentId/credentials with auth, OPA, and rateLimit middleware.
 */

import { Router, RequestHandler } from 'express';
import { CredentialController } from '../controllers/CredentialController.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 credential management endpoints.
 * This router is mounted at /agents — the :agentId param is part of the path.
 *
 * @param credentialController - The credential controller instance.
 * @param opaMiddleware - The OPA authorization middleware created at startup.
 * @returns Configured Express router.
 */
export function createCredentialsRouter(credentialController: CredentialController, opaMiddleware: RequestHandler): Router {
  const router = Router({ mergeParams: true });

  router.use(asyncHandler(authMiddleware));
  router.use(opaMiddleware);
  router.use(asyncHandler(rateLimitMiddleware));

  // POST /agents/:agentId/credentials — Generate new credentials
  router.post('/', asyncHandler(credentialController.generateCredential.bind(credentialController)));

  // GET /agents/:agentId/credentials — List credentials
  router.get('/', asyncHandler(credentialController.listCredentials.bind(credentialController)));

  // POST /agents/:agentId/credentials/:credentialId/rotate — Rotate a credential
  router.post('/:credentialId/rotate', asyncHandler(credentialController.rotateCredential.bind(credentialController)));

  // DELETE /agents/:agentId/credentials/:credentialId — Revoke a credential
  router.delete('/:credentialId', asyncHandler(credentialController.revokeCredential.bind(credentialController)));

  return router;
}
