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 {
  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) : "—";
  }
  return "—";
}

function date(d: unknown): string {
  return d ? new Date(d as string).toLocaleDateString() : "—";
}

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

  const { data: applications } = await supabase
    .from("student_applications")
    .select(
      "applicant_name, status, created_at, institute:institutes(name)",
    )
    .eq("offer_received", false)
    .order("created_at", { ascending: false });

  const columns: ReportColumn[] = [
    { key: "applicant", label: "Applicant" },
    { key: "institute", label: "Institute" },
    { key: "status", label: "Status" },
    { key: "created", label: "Created" },
  ];

  const rows = (applications ?? []).map((a) => ({
    applicant: a.applicant_name ?? "—",
    institute: name(a.institute),
    status: a.status ?? "—",
    created: date(a.created_at),
  }));

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