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 `title`. */
function title(x: unknown): string | null {
  const row = Array.isArray(x) ? x[0] : x;
  if (row && typeof row === "object" && "title" in row) {
    const t = (row as { title?: unknown }).title;
    return t ? String(t) : null;
  }
  return null;
}

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

  const { data: applications } = await supabase
    .from("student_applications")
    .select("course:courses(title)");

  const counts = new Map<string, number>();
  for (const a of applications ?? []) {
    const key = title(a.course) ?? "Unknown";
    counts.set(key, (counts.get(key) ?? 0) + 1);
  }

  const columns: ReportColumn[] = [
    { key: "course", label: "Course" },
    { key: "applications", label: "Applications", numeric: true },
  ];

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

  return (
    <ReportTable
      title="Most Preferred Courses Report"
      breadcrumb="Home / Reports / Most Preferred Courses"
      columns={columns}
      rows={rows}
    />
  );
}
