import { GetStaticPaths, GetStaticPathsContext, GetStaticProps, GetStaticPropsContext } from 'next'
import { getGlobalFields } from '@/lib/api/globals'
import { getAllProductPageSlugs, getProductPageBySlug } from '@/lib/api/products'
import { getAllPostSlugs, getPostBySlug } from '@/lib/api/posts'
import { nodesFromEdges } from '@/lib/utilities'
import type { PreviewData } from '@/lib/types'

// Products
export const productGetStaticPropsHelper = async (
  { params, preview = false }: GetStaticPropsContext,
  slugPrefix: string = 'optional-slug-prefix/'
) => {
  const { globals } = await getGlobalFields(preview)

  try {
    const { page } = await getProductPageBySlug(`${slugPrefix + 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 productGetStaticPathsHelper: GetStaticPaths = async () => {
  const products = await getAllProductPageSlugs()

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

// Blog/news/events
export const blogGetStaticPropsHelper: GetStaticProps = async ({ params, preview = false, previewData }) => {
  const { globals } = await getGlobalFields(preview)

  try {
    const { page, morePosts } = await getPostBySlug(`${params?.slug}`, preview, previewData as PreviewData)

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

    const allMorePosts = nodesFromEdges(morePosts.edges)

    return {
      props: {
        key: page.id,
        globals,
        page,
        morePosts: allMorePosts,
        preview,
      },
      revalidate: 10,
    }
  } catch (error) {
    return {
      props: {
        globals,
        preview,
      },
      notFound: true,
      revalidate: 10,
    }
  }
}

export const blogGetStaticPathsHelper = async (context: GetStaticPathsContext, category: string) => {
  const posts = await getAllPostSlugs()

  return {
    paths:
      posts.filter(node => node.uri.startsWith(`/${category}`)).map(node => ({ params: { slug: node.slug } })) || [],
    fallback: 'blocking',
  }
}
