import type { Metadata } from "next";
import { notFound } from "next/navigation";
import BlockRenderer from "@/components/blocks/BlockRenderer";
import { getPageBySlug } from "@/lib/api";

export const revalidate = 300; // ISR: re-fetch content every 5 minutes

/**
 * Catch-all for any CMS page beyond the home page — the Page Builder's "New
 * Page" flow can publish any slug/route (e.g. slug "about", route "/about"),
 * but until this route existed there was no Next.js page capable of serving
 * it (only "/" and "/forms/[formKey]" were wired up), so a second published
 * page 404'd regardless of the CMS. Single dynamic segment only — matches
 * what the Page Builder actually produces today (no nested/multi-segment
 * routes in the admin UI).
 */

// Requests like /favicon.ico or /robots.txt (no matching file under public/) land
// here too since this is a catch-all — treat anything with a file extension as a
// static-asset miss rather than spending an API call + logging a spurious 500.
function looksLikeStaticAsset(slug: string): boolean {
  return /\.[a-z0-9]+$/i.test(slug);
}

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params;
  if (looksLikeStaticAsset(slug)) return {};
  const page = await getPageBySlug(slug);
  if (!page) return {};
  return {
    title: page.metaTitle || page.title || undefined,
    description: page.metaDescription || undefined
  };
}

export default async function CmsPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  if (looksLikeStaticAsset(slug)) notFound();
  const page = await getPageBySlug(slug);

  if (!page?.layoutJson) notFound();

  return <BlockRenderer blocks={page.layoutJson.blocks} />;
}
