/**
 * GET /api/dashboard/channel-breakdown?brandId=…&range=28d&attribution=first
 *
 * Returns conversion counts grouped by classifiedChannel for the
 * Conversions by Source dashboard component. Excludes duplicates
 * and invalidated rows via the active filter.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { rangeToDays } from "@/lib/services/date-utils";
import { countedConversionWhere } from "@/lib/conversions/counted-where";

export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");
  const range = searchParams.get("range") ?? "28d";

  if (!brandId) return NextResponse.json({ channels: [] });

  const days = rangeToDays(range);
  const since = new Date(Date.now() - days * 86_400_000);
  const prevSince = new Date(since.getTime() - days * 86_400_000);

  const [current, previous] = await Promise.all([
    prisma.siteConversion.groupBy({
      by: ["classifiedChannel"],
      where: {
        ...countedConversionWhere(brandId, { since }),
        classifiedChannel: { not: null },
      },
      _count: true,
    }).catch(() => []),

    prisma.siteConversion.groupBy({
      by: ["classifiedChannel"],
      where: {
        ...countedConversionWhere(brandId),
        timestamp: { gte: prevSince, lt: since },
        classifiedChannel: { not: null },
      },
      _count: true,
    }).catch(() => []),
  ]);

  const prevMap = new Map(previous.map((p) => [p.classifiedChannel, typeof p._count === "number" ? p._count : 0]));

  const channels = current
    .map((c) => {
      const count = typeof c._count === "number" ? c._count : 0;
      const prevCount = prevMap.get(c.classifiedChannel) ?? 0;
      const delta = prevCount > 0 ? Math.round(((count - prevCount) / prevCount) * 100) : 0;
      return {
        channel: c.classifiedChannel as string,
        count,
        delta,
        prevCount,
      };
    })
    .sort((a, b) => b.count - a.count);

  const total = channels.reduce((s, c) => s + c.count, 0);

  return NextResponse.json({ channels, total, range, days });
}
