import { PeopleList, type ListPerson } from "@/components/PeopleList";
import type { ItemKind } from "@/db/schema";
import { listPeople } from "@/lib/data";
import { KIND_ORDER } from "@/lib/kinds";

export default async function Home({ searchParams }: PageProps<"/">) {
  const { ospiti } = await searchParams;
  const people = await listPeople();

  const list: ListPerson[] = people.map((p) => {
    const counts = Object.fromEntries(KIND_ORDER.map((k) => [k, p.items.filter((i) => i.kind === k && !i.parentId).length])) as Record<ItemKind, number>;
    const labels = KIND_ORDER.flatMap((kind) => p.items.filter((i) => i.kind === kind).map((i) => ({ kind, label: i.label })));
    return { id: p.id, name: p.name, notes: p.notes, updatedBy: p.updatedBy, counts, labels };
  });

  const preselected = typeof ospiti === "string" ? ospiti.split(",").filter((id) => list.some((p) => p.id === id)) : [];

  return <PeopleList people={list} preselected={preselected} />;
}
