/**
 * GET /api/agent/routing
 *
 * Returns routing history and active routes.
 * Query params:
 *   ?status=active|matched|completed|expired  (filter by status)
 *   ?sender=0x...                             (filter by sender)
 *   ?limit=10                                 (max results, default 20)
 *
 * Also returns aggregate stats for the routing dashboard.
 */

import { NextResponse } from 'next/server';
import { getRoutes, getRouteById } from '../route/route';

const CORS = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type',
};

export async function OPTIONS() {
  return new NextResponse(null, { status: 204, headers: CORS });
}

export async function GET(req: Request) {
  try {
    const url = new URL(req.url);
    const statusFilter = url.searchParams.get('status');
    const senderFilter = url.searchParams.get('sender');
    const routeIdParam = url.searchParams.get('routeId');
    const limit = Math.min(parseInt(url.searchParams.get('limit') || '20'), 50);

    // Single route lookup
    if (routeIdParam) {
      const route = getRouteById(routeIdParam);
      if (!route) {
        return NextResponse.json(
          { error: 'Route not found' },
          { status: 404, headers: CORS },
        );
      }
      return NextResponse.json(route, { headers: CORS });
    }

    // Get all routes
    let routes = getRoutes();

    // Apply filters
    if (statusFilter) {
      routes = routes.filter(r => r.status === statusFilter);
    }
    if (senderFilter) {
      routes = routes.filter(r =>
        r.senderAddress.toLowerCase() === senderFilter.toLowerCase(),
      );
    }

    // Limit
    const limited = routes.slice(0, limit);

    // Compute aggregate stats
    const allRoutes = getRoutes();
    const stats = {
      totalRoutes: allRoutes.length,
      activeRoutes: allRoutes.filter(r => r.status === 'active').length,
      matchedRoutes: allRoutes.filter(r => r.status === 'matched').length,
      completedRoutes: allRoutes.filter(r => r.status === 'completed').length,
      avgMatchScore: allRoutes.length > 0
        ? Math.round(
            allRoutes.reduce((sum, r) => {
              const topMatch = r.candidates[0]?.matchScore ?? 0;
              return sum + topMatch;
            }, 0) / allRoutes.length,
          )
        : 0,
      chainsActive: 4,
      lastRouteAt: allRoutes[0]?.routedAt ?? null,
    };

    return NextResponse.json({
      routes: limited,
      stats,
      timestamp: Date.now(),
    }, { headers: CORS });

  } catch {
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500, headers: CORS },
    );
  }
}
