import { getClient } from "@/app/client";
import {
  type SearchResult,
  SearchResults,
} from "@/components/search/SearchResults";
import { SearchShell } from "@/components/search/SearchShell";
import { graphql } from "@/gql";

// TODO: seo metadata?

export default async function Page({
  searchParams,
}: {
  searchParams?: Promise<{
    q?: string;
  }>;
}) {
  const { q: query } = (await searchParams) ?? {};
  let results: SearchResult[] = [];
  let totalCount = 0;
  const RESULT_LIMIT = 500;

  if (query) {
    const searchQuery = graphql(`
      query search($query: String) {
        results: search(query: $query) {
          __typename
          ... on PageInterface {
            id
            title
            url
          }
          ... on NewsPage {
            excerpt
            featuredImage {
              ...Image
            }
            firstPublishedAt
          }
          ... on EventPage {
            subtitle
            featuredImage {
              ...Image
            }
            occurrences {
              start
            }
          }
          ... on GenericPage {
            lead
          }
          ... on VenuePage {
            featuredImage {
              ...Image
            }
          }
          ... on AssociationPage {
            excerpt
            associationType
            logo {
              ...Image
            }
          }
        }
      }
    `);

    const { data } = await getClient().query(searchQuery, { query });
    const all = (data?.results ?? []) as SearchResult[];
    totalCount = all.length;
    results = all.slice(0, RESULT_LIMIT);
  }

  return (
    <main className="site-main" id="main">
      <SearchShell initialQuery={query ?? ""}>
        {query ? (
          <SearchResults
            results={results}
            totalCount={totalCount}
            query={query}
          />
        ) : null}
      </SearchShell>
    </main>
  );
}
