import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { logger } from "@/lib/logger";
import {
  getTokenSpending,
  getCloudSpending,
  getSavingsEstimate,
  formatSpendingContext,
} from "@/lib/token/analytics";

/**
 * GET /api/token/analytics — Fetch cost analytics for the current user.
 *
 * Returns Token assistant spending, cloud API spending, and savings estimates.
 * 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 [tokenSpending, cloudSpending, savings] = await Promise.all([
      getTokenSpending(session.user.id),
      getCloudSpending(session.user.id),
      getSavingsEstimate(session.user.id),
    ]);

    const formatted = formatSpendingContext(tokenSpending, cloudSpending, savings);

    logger.info(
      { action: "token_analytics_fetch", user_id: session.user.id },
      "Token analytics fetched",
    );

    return NextResponse.json({
      tokenSpending,
      cloudSpending,
      savings,
      formatted,
    });
  } catch (err) {
    logger.error({ err, action: "token_analytics_error" }, "Failed to fetch Token analytics");
    return NextResponse.json(
      { error: "Failed to load analytics" },
      { status: 500 },
    );
  }
}
