import { requireSession } from "@/lib/auth/guards";
import { getFacets } from "@/lib/search/facets";
import { parseSearchParams } from "@/lib/search/parse-params";
import { searchEquipment } from "@/lib/search/query-equipment";
import { SearchTabs } from "@/components/search/SearchTabs";
import { SearchBar } from "@/components/search/SearchBar";
import { FilterPanel } from "@/components/search/FilterPanel";
import { ResultList } from "@/components/search/results/ResultList";
import { EquipmentResultRow } from "@/components/search/results/EquipmentResultRow";
import { de } from "@/lib/i18n/de";

type SearchParamsRecord = Record<string, string | string[] | undefined>;

export default async function GeraetePage({
  searchParams,
}: {
  searchParams: Promise<SearchParamsRecord>;
}) {
  // Default-deny in der Tiefe (Querschnittsstandard 1).
  await requireSession();

  const sp = await searchParams;
  const facets = await getFacets("equipment");
  const params = parseSearchParams(sp, facets);
  const categoryRaw = Array.isArray(sp.kategorie) ? sp.kategorie[0] : sp.kategorie;
  const hits = await searchEquipment({
    ...params,
    categoryId:
      categoryRaw &&
      /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
        categoryRaw,
      )
        ? categoryRaw
        : undefined,
  });

  return (
    <div className="flex flex-col gap-4">
      <h1 className="text-xl font-semibold text-navy">{de.nav.geraete}</h1>
      <SearchTabs />
      <SearchBar />
      <div className="grid grid-cols-1 gap-6 md:grid-cols-[16rem_1fr]">
        <FilterPanel facets={facets} />
        <ResultList count={hits.length}>
          {hits.map((hit) => (
            <EquipmentResultRow key={hit.entityId} hit={hit} />
          ))}
        </ResultList>
      </div>
    </div>
  );
}
