import React from "react";
import { NextPage, GetStaticProps, GetStaticPaths } from "next";
import Head from "next/head";
import { useRouter } from "next/router";
import Post from "@models/Feed";
import FeedApi from "@api/feedApi";
import FeedPageView from "@views/FeedPage/FeedPageView";
import PageWrapper from "@views/common/PageWrapper";
import LoadingView from "@views/common/LoadingView";

interface InitialProps {
  post: Post;
}

const FeedPage: NextPage<InitialProps> = ({ post }) => {
  const router = useRouter();
  const { id } = router.query;

  if (router.isFallback) return <LoadingView />;

  return (
    <>
      <Head>
        <link rel="canonical" href={`${process.env.NEXT_PUBLIC_SITE_URL}/feed/${id}`} />
      </Head>
      <PageWrapper>
        <FeedPageView post={post} />
      </PageWrapper>
    </>
  );
};

export const getStaticPaths: GetStaticPaths = async () => {
  const feed = await FeedApi.getFeed();
  const paths = feed.map((post: Post) => ({
    params: {
      id: String(post.id),
    },
  }
  ));
  return {
    paths,
    fallback: true,
  };
};

export const getStaticProps: GetStaticProps<InitialProps> = async ({ params }) => {
  const { id } = params;
  let notFound = false;
  let post: Post;
  try {
    post = await FeedApi.getPost(Number(id));
  } catch (err) {
    notFound = true;
  }

  return {
    props: {
      post,
    },
    revalidate: 10, // Required for deleting hidden pages
    notFound,
  };
};

export default FeedPage;
