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 named field. */
function field(x: unknown, key: string): string {
  const row = Array.isArray(x) ? x[0] : x;
  if (row && typeof row === "object" && key in row) {
    const v = (row as Record<string, unknown>)[key];
    return v ? String(v) : "—";
  }
  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), type:application_types(name), counselor:users(full_name)",
    )
    .order("created_at", { ascending: false });

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

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

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