/**
 * GET /api/admin/ai-usage — AI usage analytics.
 */
import { NextResponse } from "next/server";
import { requireAdmin } from "@/lib/admin-auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const auth = await requireAdmin();
  if (!auth.ok) return NextResponse.json({ error: "Forbidden" }, { status: auth.status });
  const days = Math.max(1, Math.min(90, Number(new URL(req.url).searchParams.get("days") || 30)));
  const since = new Date(Date.now() - days * 86400000);

  const [byFeature, totalCost, totalCalls, topBrands] = await Promise.all([
    prisma.aiUsageLog.groupBy({ by: ["feature"], where: { timestamp: { gte: since } }, _count: true, _sum: { estimatedCost: true } }),
    prisma.aiUsageLog.aggregate({ where: { timestamp: { gte: since } }, _sum: { estimatedCost: true, inputTokens: true, outputTokens: true } }),
    prisma.aiUsageLog.count({ where: { timestamp: { gte: since } } }),
    prisma.aiUsageLog.groupBy({ by: ["brandId"], where: { timestamp: { gte: since }, brandId: { not: null } }, _sum: { estimatedCost: true }, _count: true, orderBy: { _sum: { estimatedCost: "desc" } }, take: 10 }),
  ]);

  return NextResponse.json({
    totalCalls, totalCost: Math.round((totalCost._sum.estimatedCost ?? 0) * 100) / 100,
    totalInputTokens: totalCost._sum.inputTokens ?? 0, totalOutputTokens: totalCost._sum.outputTokens ?? 0,
    byFeature: byFeature.map((f) => ({ feature: f.feature, calls: f._count, cost: Math.round((f._sum.estimatedCost ?? 0) * 100) / 100 })),
    topBrands: topBrands.map((b) => ({ brandId: b.brandId, calls: b._count, cost: Math.round((b._sum.estimatedCost ?? 0) * 100) / 100 })),
  });
}
