/**
 * GET /api/dashboard/channel-drilldown?brandId=…&channel=organic_search&range=28d
 *
 * Returns drill-down data for a single classified channel:
 *   - top sources (firstTouchSource)
 *   - top landing pages (pageUrl)
 *   - conversion type breakdown
 */

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 channel = searchParams.get("channel");
  const range = searchParams.get("range") ?? "28d";

  if (!brandId || !channel) {
    return NextResponse.json({ sources: [], pages: [], types: [] });
  }

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

  const baseWhere = {
    ...countedConversionWhere(brandId, { since }),
    classifiedChannel: channel,
  };

  const [sources, pages, types] = await Promise.all([
    prisma.siteConversion.groupBy({
      by: ["firstTouchSource"],
      where: baseWhere,
      _count: true,
      orderBy: { _count: { firstTouchSource: "desc" } },
      take: 20,
    }).catch(() => []),

    prisma.siteConversion.groupBy({
      by: ["pageUrl"],
      where: baseWhere,
      _count: true,
      orderBy: { _count: { pageUrl: "desc" } },
      take: 15,
    }).catch(() => []),

    prisma.siteConversion.groupBy({
      by: ["conversionType"],
      where: baseWhere,
      _count: true,
      orderBy: { _count: { conversionType: "desc" } },
    }).catch(() => []),
  ]);

  return NextResponse.json({
    sources: sources.map((s) => ({
      source: s.firstTouchSource ?? "(none)",
      count: typeof s._count === "number" ? s._count : 0,
    })),
    pages: pages.map((p) => ({
      page: p.pageUrl,
      count: typeof p._count === "number" ? p._count : 0,
    })),
    types: types.map((t) => ({
      type: t.conversionType,
      count: typeof t._count === "number" ? t._count : 0,
    })),
  });
}
