import { createClient } from "@/lib/supabase/server";
import { ReportTable } from "@/components/reports/report-table";
import type { ReportColumn } from "@/lib/types";

/** Normalize a Supabase embed (object | array | null) to the first row's `name`. */
function name(x: unknown): string | null {
  const row = Array.isArray(x) ? x[0] : x;
  if (row && typeof row === "object" && "name" in row) {
    const n = (row as { name?: unknown }).name;
    return n ? String(n) : null;
  }
  return null;
}

export default async function Page() {
  const supabase = await createClient();

  const { data: leads } = await supabase
    .from("leads")
    .select("source:lead_sources(name)");

  const counts = new Map<string, number>();
  for (const l of leads ?? []) {
    const key = name(l.source) ?? "Unknown";
    counts.set(key, (counts.get(key) ?? 0) + 1);
  }

  const columns: ReportColumn[] = [
    { key: "source", label: "Source" },
    { key: "leads", label: "Leads", numeric: true },
  ];

  const rows = Array.from(counts.entries())
    .sort((a, b) => b[1] - a[1])
    .map(([source, leads]) => ({ source, leads }));

  return (
    <ReportTable
      title="Lead Source Report"
      breadcrumb="Home / Reports / Lead Source"
      columns={columns}
      rows={rows}
    />
  );
}
