import { graphql } from "@/gql";
import { getClient } from "@/app/client";
import { SearchContainer } from "@/components/search/SearchContainer";
import { Suspense } from "react";

export default async function Page({
  searchParams,
}: {
  searchParams?: {
    q?: string;
  };
}) {
  const { q: query } = searchParams ?? {};
  let results = [];

  if (query) {
    const searchQuery = graphql(`
      query search($query: String) {
        results: search(query: $query) {
          __typename
          ... on NewsPage {
            id
            title
          }
          ... on EventPage {
            id
            title
          }
          ... on GenericPage {
            id
            title
          }
          ... on VenuePage {
            id
            title
          }
          ... on AssociationPage {
            id
            title
            associationType
          }
        }
      }
    `);

    const { data, error } = await getClient().query(searchQuery, {
      query: query,
    });

    results = (data?.results ?? []) as any;
  }

  return (
    <main className="site-main" id="main">
      <Suspense key={query}>
        <SearchContainer query={query ?? ""} results={results} />
      </Suspense>
    </main>
  );
}
