import { GetStaticPropsContext, InferGetStaticPropsType } from 'next'
import { useRouter } from 'next/router'
import getProduct from '@lib/bigcommerce/api/operations/get-product'
import { Layout } from '@components/core'
import { ProductView } from '@components/product'
import getAllProductPaths from '@lib/bigcommerce/api/operations/get-all-product-paths'

export async function getStaticProps({
  params,
}: GetStaticPropsContext<{ slug: string }>) {
  const { product } = await getProduct({ variables: { slug: params!.slug } })

  if (!product) {
    throw new Error(`Product with slug '${params!.slug}' not found`)
  }

  return {
    props: {
      product,
    },
    revalidate: 200,
  }
}

export async function getStaticPaths() {
  const { products } = await getAllProductPaths()

  return {
    paths: products.map((product) => `/product${product.node.path}`),
    fallback: false,
  }
}

export default function Slug({
  product,
}: InferGetStaticPropsType<typeof getStaticProps>) {
  const router = useRouter()

  return router.isFallback ? (
    <h1>Loading...</h1> // TODO (BC) Add Skeleton Views
  ) : (
    <ProductView product={product} />
  )
}

Slug.Layout = Layout
