import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";

export const runtime = "nodejs";

const DEFAULT_LIMIT = 50;
const MAX_LIMIT = 200;

/**
 * GET /api/dashboard/marketplace/usage
 *
 * Returns marketplace usage for the current user (session auth):
 * - totalSpendCents: sum of price_cents for the user's events
 * - events: recent MarketplaceUsageEvent rows (request_id, model, device_id, tokens, timestamp)
 */
export async function GET(request: Request) {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { searchParams } = new URL(request.url);
  const limit = Math.min(
    Math.max(1, parseInt(searchParams.get("limit") ?? String(DEFAULT_LIMIT), 10) || DEFAULT_LIMIT),
    MAX_LIMIT
  );

  const [events, aggregate] = await Promise.all([
    db.marketplaceUsageEvent.findMany({
      where: { userId: session.user.id },
      orderBy: { createdAt: "desc" },
      take: limit,
      select: {
        id: true,
        requestId: true,
        deviceId: true,
        model: true,
        promptTokens: true,
        completionTokens: true,
        priceCents: true,
        createdAt: true,
      },
    }),
    db.marketplaceUsageEvent.aggregate({
      where: { userId: session.user.id },
      _sum: { priceCents: true },
    }),
  ]);

  const totalSpendCents = aggregate._sum.priceCents ?? 0;

  return NextResponse.json({
    totalSpendCents,
    events: events.map((e) => ({
      id: e.id,
      request_id: e.requestId,
      device_id: e.deviceId,
      model: e.model,
      prompt_tokens: e.promptTokens,
      completion_tokens: e.completionTokens,
      total_tokens: e.promptTokens + e.completionTokens,
      price_cents: e.priceCents,
      created_at: e.createdAt.toISOString(),
    })),
  });
}
