import express from "express"
import { AsyncExpressApp } from "../types.js"
import { API_BASE_ROUTE, JSON_BODY_LIMIT } from "../constants/index.js"

// Route modules
import { rootRoutes, publicApiRoutes } from "./public.routes.js"
import webhookRoutes from "./webhook.routes.js"
import optimizationRoutes from "./optimization.routes.js"
import githubRoutes from "./github.routes.js"
import subscriptionRoutes from "./subscription.routes.js"
import userRoutes from "./user.routes.js"

// Middleware
import { checkForValidAPIKey } from "../middlewares/check-valid-api-key.js"
import { trackEndpointCalls } from "../middlewares/track-endpoint-calls.js"
import { idLimiter } from "../middlewares/rate-limit.js"
import { logAuthEvent, logRequestBody } from "../middlewares/enhanced-logging.js"
/**
 * Register all routes on the Express application
 *
 * Route registration order:
 * 1. Webhook routes (must be before body parsers for raw body access)
 * 2. Body parser middleware (express.json)
 * 3. Public routes (no authentication required)
 * 4. Protected routes (require API key authentication)
 */
export function registerRoutes(app: AsyncExpressApp): void {
  // ========================================
  // WEBHOOK ROUTES (before body parsers)
  // Webhook handlers (GitHub, Stripe) need raw body access for
  // signature verification. express.json() MUST NOT run before these.
  // ========================================
  app.use(webhookRoutes)

  // ========================================
  // BODY PARSER (after webhook routes, before everything else)
  // ========================================
  app.use(express.json({ limit: JSON_BODY_LIMIT }))

  // Log request body in development
  if (process.env.NODE_ENV !== "PRODUCTION") {
    app.use(logRequestBody)
  }

  // ========================================
  // PUBLIC ROUTES (no authentication)
  // ========================================
  app.use(rootRoutes)
  app.use(API_BASE_ROUTE, publicApiRoutes)

  // ========================================
  // PROTECTED ROUTES (authentication required)
  // ========================================

  // Authentication middleware
  app.use(logAuthEvent)
  // @ts-expect-error: TS2555
  app.useAsync(checkForValidAPIKey)

  // Rate limiting
  app.use(idLimiter)

  // Analytics tracking
  app.use(trackEndpointCalls)

  // Protected route modules - all prefixed with API_BASE_ROUTE
  app.use(API_BASE_ROUTE, optimizationRoutes)
  app.use(API_BASE_ROUTE, githubRoutes)
  app.use(API_BASE_ROUTE, subscriptionRoutes)
  app.use(API_BASE_ROUTE, userRoutes)
}

export {
  rootRoutes,
  publicApiRoutes,
  webhookRoutes,
  optimizationRoutes,
  githubRoutes,
  subscriptionRoutes,
  userRoutes,
}
