/**
 * Billing routes for SentryAgent.ai AgentIdP.
 * Provides Stripe checkout, webhook processing, and usage reporting endpoints.
 */

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

/**
 * Creates and returns the Express router for billing endpoints.
 *
 * Routes:
 *   POST /billing/checkout  — authenticated; creates a Stripe Checkout Session
 *   POST /billing/webhook   — unauthenticated; receives Stripe webhook events (raw body)
 *   GET  /billing/usage     — authenticated; returns today's usage summary
 *
 * @param controller - The billing controller instance.
 * @param authMiddleware - The JWT authentication middleware for protected endpoints.
 * @returns Configured Express router.
 */
export function createBillingRouter(
  controller: BillingController,
  authMiddleware: RequestHandler,
): Router {
  const router = Router();

  // POST /billing/checkout — authenticated; creates a Stripe Checkout Session
  router.post(
    '/checkout',
    authMiddleware,
    asyncHandler(controller.createCheckoutSession.bind(controller)),
  );

  // POST /billing/webhook — unauthenticated; Stripe sends raw JSON body
  // express.raw() must be applied HERE so the body is a Buffer (required for signature verification)
  router.post(
    '/webhook',
    express.raw({ type: 'application/json' }),
    asyncHandler(controller.handleWebhook.bind(controller)),
  );

  // GET /billing/usage — authenticated; returns usage summary for today
  router.get(
    '/usage',
    authMiddleware,
    asyncHandler(controller.getUsage.bind(controller)),
  );

  return router;
}
