import { getPage, getPages, getSeoSettings } from "@/lib/api"
import { BlockRenderer } from "@/components/blocks"
import { notFound } from "next/navigation"
import type { Metadata } from "next"

export const revalidate = 60

interface PageProps {
  params: Promise<{ slug: string }>
}

export async function generateStaticParams() {
  try {
    const pages = await getPages({ limit: 100 })
    return (pages?.docs || [])
      .filter((p) => p.slug && p.slug !== "startseite")
      .map((p) => ({ slug: p.slug }))
  } catch {
    return []
  }
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params
  const [page, seoSettings] = await Promise.all([getPage(slug), getSeoSettings()])
  if (!page) return {}

  const titleSuffix = (seoSettings as Record<string, unknown>)?.metaDefaults
    ? ((seoSettings as Record<string, unknown>).metaDefaults as Record<string, unknown>)?.titleSuffix as string || ""
    : ""
  const title = page.seo?.metaTitle || page.title
  const description = page.seo?.metaDescription || ""

  return {
    title: titleSuffix ? `${title} ${titleSuffix}` : title,
    description,
  }
}

export default async function DynamicPage({ params }: PageProps) {
  const { slug } = await params
  const page = await getPage(slug)

  if (!page) notFound()

  return <BlockRenderer blocks={page.layout || []} />
}
