import EntriesExplorer from "./EntriesExplorer";
import { getEntryFacets, listGenres, listLanguages, listMachinetypes, searchEntries } from "@/server/repo";
import { parseIdList } from "@/utils/params";

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 preferredMachineIds = [27, 26, 8, 9];
  const machinetypeIds = parseIdList(sp.machinetypeId) ?? preferredMachineIds;
  const machinetypeId = machinetypeIds.join(",");
  const sort = ((Array.isArray(sp.sort) ? sp.sort[0] : sp.sort) ?? "id_desc") as "title" | "id_desc";
  const q = (Array.isArray(sp.q) ? sp.q[0] : sp.q) ?? "";
  const scope = ((Array.isArray(sp.scope) ? sp.scope[0] : sp.scope) ?? "title") as
    | "title"
    | "title_aliases"
    | "title_aliases_origins";

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

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