/**
 * Organization routes for SentryAgent.ai AgentIdP.
 * Wires OrgController handlers to Express paths with auth, OPA, and rateLimit middleware.
 */

import { Router, RequestHandler } from 'express';
import { OrgController } from '../controllers/OrgController.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 organization endpoints.
 *
 * @param orgController - The organization controller instance.
 * @param opaMiddleware - The OPA authorization middleware created at startup.
 * @returns Configured Express router.
 */
export function createOrgsRouter(orgController: OrgController, opaMiddleware: RequestHandler): Router {
  const router = Router();

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

  // POST /organizations — Create a new organization
  router.post('/', asyncHandler(orgController.createOrg.bind(orgController)));

  // GET /organizations — List organizations with optional filters
  router.get('/', asyncHandler(orgController.listOrgs.bind(orgController)));

  // GET /organizations/:orgId — Get a single organization
  router.get('/:orgId', asyncHandler(orgController.getOrg.bind(orgController)));

  // PATCH /organizations/:orgId — Update organization metadata
  router.patch('/:orgId', asyncHandler(orgController.updateOrg.bind(orgController)));

  // DELETE /organizations/:orgId — Soft-delete an organization
  router.delete('/:orgId', asyncHandler(orgController.deleteOrg.bind(orgController)));

  // POST /organizations/:orgId/members — Add an agent as a member
  router.post('/:orgId/members', asyncHandler(orgController.addMember.bind(orgController)));

  return router;
}
