/** @format */

import PageContentWithBreadcrumb from "@/components/partials/PageContentWithBreadcrumb";
import Loader from "@/components/ui/Loader";
import { getFetchInstance } from "@/configs/getFetchInstance";
import { setPageMetaData } from "@/hooks/server/pageSeoSetup";
import { notFound } from "next/navigation";
import { Suspense } from "react";

// Add this to prevent dynamic rendering
export const dynamicParams = false;

// Cache the pages data to avoid multiple API calls
let cachedPages: any[] | null = null;

async function getPages() {
  if (cachedPages !== null) {
    return cachedPages;
  }

  try {
    const response: any = await getFetchInstance({
      url: `/pages`,
    });
    cachedPages = response?.data || [];
    return cachedPages;
  } catch (error) {
    console.warn("Error fetching pages:", error);
    cachedPages = [];
    return cachedPages;
  }
}

export async function generateStaticParams() {
  try {
    const data = await getPages();

    if (!data?.length) {
      return [{ page: "not-found" }];
    }

    return data
      ?.filter((page: any) => !page?.is_default)
      .map((page: any) => ({
        page: page?.slug,
      }));
  } catch (error) {
    console.warn("Error fetching pages:", error);
    return [];
  }
}

type Props = {
  params: Promise<{ page?: string }>;
};

export async function generateMetadata({ params }: Props) {
  const { page } = await params;
  return setPageMetaData({ slug: page || "/" });
}

const DynamicPage = async ({ params }: Props) => {
  const { page } = await params;

  // Get the cached pages data
  const data = await getPages();

  const pageData = data?.find((p: any) => !p?.is_default);

  if (!pageData) {
    notFound();
  }

  return (
    <Suspense fallback={<Loader />}>
      <PageContentWithBreadcrumb page={page || "/"} />
    </Suspense>
  );
};

export default DynamicPage;
