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

/** Embeds may arrive as an array (Supabase) — normalize to the first element. */
function one<T>(v: T | T[] | null | undefined): T | null {
  if (Array.isArray(v)) return v[0] ?? null;
  return v ?? null;
}

interface ApplicationRow {
  id: string;
  applicant_name: string | null;
  status: string | null;
  created_at: string | null;
  institute: { name: string | null } | { name: string | null }[] | null;
  branch: { name: string | null } | { name: string | null }[] | null;
}

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

export default async function Page() {
  const supabase = await createClient();
  const { data } = await supabase
    .from("student_applications")
    .select(
      "id, applicant_name, status, created_at, institute:institutes(name), branch:branches(name)",
    )
    .eq("status", "Travelled")
    .order("created_at", { ascending: false });

  const applications = (data ?? []) as ApplicationRow[];

  const rows = applications.map((a) => ({
    applicant: a.applicant_name,
    institute: one(a.institute)?.name ?? null,
    branch: one(a.branch)?.name ?? null,
    status: a.status,
    created: a.created_at,
  }));

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