import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { logger } from "@/lib/logger";
import { getModelPerformance, getModelTrends } from "@/lib/token/performance";

/**
 * GET /api/token/performance — Per-model performance metrics and daily trends.
 *
 * Returns model-level aggregates (latency, cost, throughput) and daily trend
 * data for charting. Auth: NextAuth session required.
 */
export async function GET() {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const [models, trends] = await Promise.all([
      getModelPerformance(session.user.id),
      getModelTrends(session.user.id),
    ]);

    logger.info(
      {
        action: "token_performance_loaded",
        user_id: session.user.id,
        model_count: models.length,
        trend_count: trends.length,
      },
      "Performance data loaded",
    );

    return NextResponse.json({ models, trends });
  } catch (err) {
    logger.error({ err, action: "token_performance_error" }, "Failed to fetch performance data");
    return NextResponse.json(
      { error: "Failed to load performance data" },
      { status: 500 },
    );
  }
}
