import ReleasesExplorer from "./ReleasesExplorer";
import { listCasetypes, listFiletypes, listLanguages, listMachinetypes, listSchemetypes, listSourcetypes, searchReleases } from "@/server/repo";
import { parseIdList } from "@/utils/params";
import { serialize } from "@/utils/serialize";

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

export const dynamic = "force-dynamic";

export default async function Page({ searchParams }: { searchParams: Promise<{ [key: string]: string | string[] | undefined }> }) {
  const sp = await searchParams;
  const hasParams = Object.values(sp).some((value) => value !== undefined);
  const page = Math.max(1, Number(Array.isArray(sp.page) ? sp.page[0] : sp.page) || 1);
  const q = (Array.isArray(sp.q) ? sp.q[0] : sp.q) ?? "";
  const yearStr = (Array.isArray(sp.year) ? sp.year[0] : sp.year) ?? "";
  const year = yearStr ? Number(yearStr) : undefined;
  const sort = ((Array.isArray(sp.sort) ? sp.sort[0] : sp.sort) ?? "year_desc") as "year_desc" | "year_asc" | "title" | "entry_id_desc";
  const dLanguageId = (Array.isArray(sp.dLanguageId) ? sp.dLanguageId[0] : sp.dLanguageId) ?? "";
  const preferredMachineIds = [27, 26, 8, 9];
  const dMachinetypeIds = parseIdList(sp.dMachinetypeId) ?? preferredMachineIds;
  const dMachinetypeIdStr = dMachinetypeIds.join(",");
  const filetypeIdStr = (Array.isArray(sp.filetypeId) ? sp.filetypeId[0] : sp.filetypeId) ?? "";
  const filetypeId = filetypeIdStr ? Number(filetypeIdStr) : undefined;
  const schemetypeId = (Array.isArray(sp.schemetypeId) ? sp.schemetypeId[0] : sp.schemetypeId) ?? "";
  const sourcetypeId = (Array.isArray(sp.sourcetypeId) ? sp.sourcetypeId[0] : sp.sourcetypeId) ?? "";
  const casetypeId = (Array.isArray(sp.casetypeId) ? sp.casetypeId[0] : sp.casetypeId) ?? "";
  const isDemoStr = (Array.isArray(sp.isDemo) ? sp.isDemo[0] : sp.isDemo) ?? "";
  const isDemo = isDemoStr ? (isDemoStr === "true" || isDemoStr === "1") : undefined;

  const [initial, langs, machines, filetypes, schemes, sources, cases] = await Promise.all([
    searchReleases({ page, pageSize: 20, q, year, sort, dLanguageId: dLanguageId || undefined, dMachinetypeId: dMachinetypeIds, filetypeId, schemetypeId: schemetypeId || undefined, sourcetypeId: sourcetypeId || undefined, casetypeId: casetypeId || undefined, isDemo }),
    listLanguages(),
    listMachinetypes(),
    listFiletypes(),
    listSchemetypes(),
    listSourcetypes(),
    listCasetypes(),
  ]);

  return (
    <ReleasesExplorer
      initial={serialize(initial)}
      initialLists={serialize({
        languages: langs,
        machinetypes: machines,
        filetypes,
        schemetypes: schemes,
        sourcetypes: sources,
        casetypes: cases,
      })}
      initialUrlState={{ q, page, year: yearStr, sort, dLanguageId, dMachinetypeId: dMachinetypeIdStr, filetypeId: filetypeIdStr, schemetypeId, sourcetypeId, casetypeId, isDemo: isDemoStr }}
      initialUrlHasParams={hasParams}
    />
  );
}
