import { unstable_cache } from "next/cache";
import { prisma } from "@/lib/db";
import { MangaGrid } from "@/components/MangaGrid";
import type { Metadata } from "next";

export const metadata: Metadata = {
  title: "Search",
};

type Props = {
  searchParams: Promise<{ q?: string }>;
};

const searchManga = unstable_cache(
  async (q: string) =>
    prisma.manga.findMany({
      where: {
        status: "PUBLISHED",
        title: { contains: q, mode: "insensitive" },
      },
      orderBy: { title: "asc" },
      include: { _count: { select: { chapters: true } } },
    }),
  ["search-manga"],
  { revalidate: 60 }
);

export default async function SearchPage({ searchParams }: Props) {
  const { q } = await searchParams;
  const manga = q ? await searchManga(q) : [];

  return (
    <div className="max-w-7xl mx-auto px-4 py-6">
      <h1 className="text-xl font-bold mb-4">
        {q ? `Results for "${q}"` : "Search"}
      </h1>
      {q ? (
        <MangaGrid manga={manga} />
      ) : (
        <p className="text-muted text-center py-12">
          Use the search bar above to find manga
        </p>
      )}
    </div>
  );
}
