// 사이트 통합 검색 — 고객 브라우저가 아니라 이 Server Component가 CMS API를 호출한다.
import type { Metadata } from "next";
import Link from "next/link";

import {
  fetchCollections,
  resolveSearchHitPath,
  searchPosts,
} from "@roottale/cms-client/server";

export const metadata: Metadata = {
  title: "사이트 검색",
  robots: { index: false, follow: true },
};

interface Props {
  searchParams: Promise<{ q?: string | string[] }>;
}

export default async function SearchPage({ searchParams }: Props) {
  const { q = "" } = await searchParams;
  const query = (typeof q === "string" ? q : q[0] ?? "").trim();
  const apiKey = process.env.ROOTTALE_API_KEY!;
  const baseUrl = process.env.ROOTTALE_API_BASE;
  const [hits, collections] = query
    ? await Promise.all([
        searchPosts({ apiKey, baseUrl, query, type: "all", limit: 20 }),
        fetchCollections({ apiKey, baseUrl }).catch(() => []),
      ])
    : [[], []];

  return (
    <main>
      <h1>사이트 검색</h1>
      <form action="/search" method="get" role="search">
        <label htmlFor="site-search">검색어</label>
        <input
          defaultValue={query}
          id="site-search"
          maxLength={100}
          name="q"
          required
          type="search"
        />
        <button type="submit">검색</button>
      </form>
      {query ? <p>검색 결과 {hits.length}건</p> : <p>검색어를 입력해 주세요.</p>}
      <ul>
        {hits.map((hit) => {
          const href = resolveSearchHitPath(hit, collections);
          if (!href) return null;
          return (
            <li key={hit.id}>
              <Link href={href}>
                <h2>{hit.title}</h2>
                {hit.excerpt ? <p>{hit.excerpt}</p> : null}
              </Link>
            </li>
          );
        })}
      </ul>
    </main>
  );
}
