import EntriesExplorer from "./EntriesExplorer";
import { listGenres, listLanguages, listMachinetypes, searchEntries } from "@/server/repo/zxdb";

export const metadata = {
  title: "ZXDB Entries",
};

export const dynamic = "force-dynamic";

export default async function Page({ searchParams }: { searchParams: Promise<{ [key: string]: string | string[] | undefined }> }) {
  const sp = await searchParams;
  const page = Math.max(1, Number(Array.isArray(sp.page) ? sp.page[0] : sp.page) || 1);
  const genreId = (Array.isArray(sp.genreId) ? sp.genreId[0] : sp.genreId) ?? "";
  const languageId = (Array.isArray(sp.languageId) ? sp.languageId[0] : sp.languageId) ?? "";
  const machinetypeId = (Array.isArray(sp.machinetypeId) ? sp.machinetypeId[0] : sp.machinetypeId) ?? "";
  const sort = ((Array.isArray(sp.sort) ? sp.sort[0] : sp.sort) as any) ?? "id_desc";
  const q = (Array.isArray(sp.q) ? sp.q[0] : sp.q) ?? "";

  const [initial, genres, langs, machines] = await Promise.all([
    searchEntries({
      page,
      pageSize: 20,
      sort,
      q,
      genreId: genreId ? Number(genreId) : undefined,
      languageId: languageId || undefined,
      machinetypeId: machinetypeId ? Number(machinetypeId) : undefined,
    }),
    listGenres(),
    listLanguages(),
    listMachinetypes(),
  ]);

  return (
    <EntriesExplorer
      initial={initial as any}
      initialGenres={genres as any}
      initialLanguages={langs as any}
      initialMachines={machines as any}
      initialUrlState={{ q, page, genreId, languageId, machinetypeId, sort }}
    />
  );
}
