import type { GetStaticPaths, GetStaticProps, InferGetStaticPropsType } from 'next'

import { getGlobalFields } from '@/lib/api/globals'
import { getAllCaseStudySlugs, getCaseStudyBySlug } from '@/lib/api/case-studies'

import SingleTemplate from '@/components/templates/Single'

export default function CaseStudy({ page }: InferGetStaticPropsType<typeof getStaticProps>) {
  return <SingleTemplate postType="case_study" page={page} />
}

export const getStaticProps: GetStaticProps = async ({ params, preview = false }) => {
  const { globals } = await getGlobalFields(preview)

  try {
    const { page } = await getCaseStudyBySlug(`${params?.slug}`)

    if (!page) throw new Error('Does not exist.')

    return {
      props: {
        key: page.id,
        globals,
        page,
        preview,
      },
      revalidate: 10,
    }
  } catch (error) {
    console.error(error)

    return {
      props: {
        globals,
        preview,
      },
      notFound: true,
      revalidate: 10,
    }
  }
}

export const getStaticPaths: GetStaticPaths = async () => {
  const caseStudies = await getAllCaseStudySlugs()

  return {
    paths: caseStudies.map(node => ({ params: { slug: node.slug } })) || [],
    fallback: 'blocking',
  }
}
