import { notFound } from 'next/navigation'
import { getPayload } from 'payload'
import React from 'react'
import { RichText } from '@payloadcms/richtext-lexical/react'

import config from '@/payload.config'
import type { Page } from '@/payload-types'
import '../styles.css'

export const dynamic = 'force-dynamic'

type Props = { params: Promise<{ slug: string }> }

export async function generateMetadata({ params }: Props) {
  const stranka = await najdiStranku((await params).slug)
  return { title: stranka ? `${stranka.nazev} — Reiner zbraně` : 'Stránka nenalezena' }
}

/** Statické stránky z kolekce Pages — /kontakt, /o-nas a podobně. */
export default async function StatickaStranka({ params }: Props) {
  const stranka = await najdiStranku((await params).slug)
  if (!stranka) notFound()

  return (
    <article className="stranka">
      <h1>{stranka.nazev}</h1>
      {stranka.obsah && <RichText data={stranka.obsah} />}
    </article>
  )
}

async function najdiStranku(slug: string): Promise<Page | null> {
  const payload = await getPayload({ config: await config })

  const { docs } = await payload.find({
    collection: 'pages',
    where: { slug: { equals: slug } },
    limit: 1,
  })

  return docs[0] ?? null
}
