import Layout from "@/layouts/main";
import Main from "@/components/pages/blog/slug";
import { GetStaticPaths, GetStaticProps } from "next";
import datasquirel from "@moduletrace/datasquirel";
import { PagePropsType } from "@/types";
import { APIResponseObject } from "@moduletrace/datasquirel/dist/package-shared/types";
import { serialize } from "next-mdx-remote/serialize";
import remarkGfm from "remark-gfm";
import rehypePrismPlus from "rehype-prism-plus";
import matter from "gray-matter";
import { DSQL_TBEN_ME_BLOG_POSTS } from "@/types/dsql";

export default function SingleBlogPost({ blogPost }: PagePropsType) {
    return (
        <Layout
            meta={{
                title: blogPost?.meta_title,
                description: blogPost?.meta_description,
            }}
        >
            <Main />
        </Layout>
    );
}

export const getStaticProps: GetStaticProps<PagePropsType> = async (ctx) => {
    const blogPostRes: APIResponseObject<DSQL_TBEN_ME_BLOG_POSTS> =
        await datasquirel.crud<DSQL_TBEN_ME_BLOG_POSTS>({
            action: "get",
            table: "blog_posts",
            query: {
                query: {
                    slug: {
                        value: ctx.params?.slug,
                    },
                    published: {
                        value: "1",
                    },
                },
            },
        });

    const singleBlogPost = blogPostRes.payload?.[0] || null;

    if (!singleBlogPost?.body) {
        return {
            props: {},
        };
    }

    const pageMdString = singleBlogPost.body;

    const pageGrayMatter = matter(pageMdString);

    const data = pageGrayMatter.data;
    const content = pageGrayMatter.content;

    const mdxSource = await serialize(content, {
        mdxOptions: {
            remarkPlugins: [remarkGfm],
            rehypePlugins: [rehypePrismPlus],
        },
        scope: data,
    });

    return {
        props: {
            blogPost: singleBlogPost,
            mdxSource,
        },
        revalidate: 3600,
    };
};

export const getStaticPaths: GetStaticPaths = async (ctx) => {
    const blogPostRes: APIResponseObject<DSQL_TBEN_ME_BLOG_POSTS> =
        await datasquirel.crud<DSQL_TBEN_ME_BLOG_POSTS>({
            action: "get",
            table: "blog_posts",
            query: {
                query: {
                    published: {
                        value: "1",
                    },
                },
            },
        });

    const blogPosts = blogPostRes.payload;

    if (!blogPosts?.[0]) {
        return {
            paths: [],
            fallback: "blocking",
        };
    }

    return {
        paths: blogPosts.map((post) => {
            return {
                params: {
                    slug: post.slug,
                },
            };
        }),
        fallback: "blocking",
    };
};
