import type { Metadata } from 'next'
import { setRequestLocale } from 'next-intl/server'
import { CaseStudyView } from '@/components/case-study-view'
import { JsonLd } from '@/components/seo/json-ld'
import type { Locale } from '@/i18n/config'
import type { CaseStudy } from '@/lib/api/entities'
import { buildShareMetadata } from '@/lib/metadata'
import { fetchSeoRecord, seoDescription } from '@/lib/seo-data'
import { getStaticSiteSettings } from '@/lib/site-settings'
import {
  buildBreadcrumbJsonLd,
  buildCaseStudyJsonLd,
} from '@/lib/structured-data'

type CaseStudyPageProps = {
  params: Promise<{ locale: string; slug: string }>
}

export async function generateMetadata({ params }: CaseStudyPageProps): Promise<Metadata> {
  const { locale, slug } = await params
  const site = getStaticSiteSettings()
  const study = await fetchSeoRecord<CaseStudy>('case-studies', slug, locale)

  if (!study) {
    return { title: 'Case study not found', robots: { index: false, follow: false } }
  }

  return buildShareMetadata({
    title: study.title,
    description: seoDescription(study.challenge || study.solution, site.description),
    path: `/resources/case-studies/${study.slug}`,
    image: study.image,
    imageAlt: study.title,
    site,
    locale,
    type: 'article',
  })
}

export default async function CaseStudyPage({ params }: CaseStudyPageProps) {
  const { locale, slug } = await params
  setRequestLocale(locale)
  const site = getStaticSiteSettings()
  const study = await fetchSeoRecord<CaseStudy>('case-studies', slug, locale)
  const resolvedLocale = locale as Locale

  return (
    <>
      {study ? (
        <JsonLd
          data={[
            buildCaseStudyJsonLd(study, resolvedLocale, site),
            buildBreadcrumbJsonLd(
              [
                { name: 'Home', path: '/' },
                { name: 'Case Studies', path: '/resources/case-studies' },
                { name: study.title, path: `/resources/case-studies/${study.slug}` },
              ],
              resolvedLocale,
              site,
            ),
          ]}
        />
      ) : null}
      <CaseStudyView />
    </>
  )
}
