/**
 * Webhook routes — subscription management and delivery history.
 *
 * All endpoints require authentication (authMiddleware) and OPA scope enforcement.
 *
 * Endpoints:
 *   POST   /webhooks                     → createSubscription  (webhooks:write)
 *   GET    /webhooks                     → listSubscriptions   (webhooks:read)
 *   GET    /webhooks/:id                 → getSubscription     (webhooks:read)
 *   PATCH  /webhooks/:id                 → updateSubscription  (webhooks:write)
 *   DELETE /webhooks/:id                 → deleteSubscription  (webhooks:write)
 *   GET    /webhooks/:id/deliveries      → listDeliveries      (webhooks:read)
 *
 * Mount this router at `${API_BASE}/webhooks` in app.ts.
 */

import { Router, RequestHandler } from 'express';
import { WebhookController } from '../controllers/WebhookController.js';
import { asyncHandler } from '../utils/asyncHandler.js';

/**
 * Creates and returns the Express router for webhook endpoints.
 * Mount at `${API_BASE}/webhooks` (i.e. `/api/v1/webhooks`) in app.ts.
 *
 * @param controller - The webhook controller instance.
 * @param authMiddleware - JWT authentication middleware.
 * @param opaMiddleware - OPA authorization middleware (scope enforcement).
 * @returns Configured Express router.
 */
export function createWebhooksRouter(
  controller: WebhookController,
  authMiddleware: RequestHandler,
  opaMiddleware: RequestHandler,
): Router {
  const router = Router();

  // POST /webhooks — create a new subscription (webhooks:write)
  router.post(
    '/',
    authMiddleware,
    opaMiddleware,
    asyncHandler(controller.createSubscription.bind(controller)),
  );

  // GET /webhooks — list all subscriptions for the org (webhooks:read)
  router.get(
    '/',
    authMiddleware,
    opaMiddleware,
    asyncHandler(controller.listSubscriptions.bind(controller)),
  );

  // GET /webhooks/:id — get a single subscription (webhooks:read)
  router.get(
    '/:id',
    authMiddleware,
    opaMiddleware,
    asyncHandler(controller.getSubscription.bind(controller)),
  );

  // PATCH /webhooks/:id — update a subscription (webhooks:write)
  router.patch(
    '/:id',
    authMiddleware,
    opaMiddleware,
    asyncHandler(controller.updateSubscription.bind(controller)),
  );

  // DELETE /webhooks/:id — delete a subscription (webhooks:write)
  router.delete(
    '/:id',
    authMiddleware,
    opaMiddleware,
    asyncHandler(controller.deleteSubscription.bind(controller)),
  );

  // GET /webhooks/:id/deliveries — list delivery history (webhooks:read)
  router.get(
    '/:id/deliveries',
    authMiddleware,
    opaMiddleware,
    asyncHandler(controller.listDeliveries.bind(controller)),
  );

  return router;
}
