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

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

export const dynamic = "force-dynamic";

function parseIdList(value: string | string[] | undefined) {
  if (!value) return undefined;
  const raw = Array.isArray(value) ? value.join(",") : value;
  const ids = raw
    .split(",")
    .map((id) => Number(id.trim()))
    .filter((id) => Number.isFinite(id) && id > 0);
  return ids.length ? ids : undefined;
}

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(),
  ]);

  // Ensure the object passed to a Client Component is a plain JSON value
  const initialPlain = JSON.parse(JSON.stringify(initial));

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