/**
 * GET /api/client-portal/conversions?brandId=X
 * Client-facing conversion summary from SiteConversion.
 */

import { NextResponse } from "next/server";
import { requireClientAuth, pageAllowed } from "@/lib/client-auth";
import { prisma } from "@/lib/prisma";
import { countedConversionWhere } from "@/lib/conversions/counted-where";

export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const brandId = new URL(req.url).searchParams.get("brandId") || "";
  const auth = await requireClientAuth(brandId);
  if (!auth.ok) return NextResponse.json({ error: auth.error }, { status: auth.status });
  if (!pageAllowed(auth.session, "conversions")) return NextResponse.json({ error: "Page not allowed" }, { status: 403 });

  const since = new Date(Date.now() - 30 * 86400000);
  const rows = await prisma.siteConversion.findMany({
    where: countedConversionWhere(brandId, { since }),
    select: { conversionType: true, lastTouchChannel: true, pageUrl: true },
  });

  const byType = new Map<string, number>();
  const byChannel = new Map<string, number>();
  for (const r of rows) {
    byType.set(r.conversionType, (byType.get(r.conversionType) || 0) + 1);
    const ch = r.lastTouchChannel || "direct";
    byChannel.set(ch, (byChannel.get(ch) || 0) + 1);
  }

  return NextResponse.json({
    total: rows.length,
    period: "30d",
    byType: Array.from(byType.entries()).map(([type, count]) => ({ type, count })).sort((a, b) => b.count - a.count),
    byChannel: Array.from(byChannel.entries()).map(([channel, count]) => ({ channel, count })).sort((a, b) => b.count - a.count),
  });
}
