import type { ReactNode } from "react";
import { unstable_noStore as noStore } from "next/cache";
import { NextIntlClientProvider } from "next-intl";
import { getMessages, setRequestLocale } from "next-intl/server";
import { notFound } from "next/navigation";

import { routing } from "@/i18n/routing";
import { getDirection } from "@/lib/locale";

type LocaleLayoutProps = {
  children: ReactNode;
  params: {
    locale: string;
  };
};

export const dynamic = "force-dynamic";
export const revalidate = 0;

export function generateStaticParams() {
  return routing.locales.map((locale) => ({ locale }));
}

export default async function LocaleLayout({
  children,
  params: { locale },
}: LocaleLayoutProps) {
  noStore();

  if (!routing.locales.includes(locale as (typeof routing.locales)[number])) {
    notFound();
  }

  setRequestLocale(locale);

  const messages = await getMessages();

  return (
    <NextIntlClientProvider messages={messages}>
      <div lang={locale} dir={getDirection(locale)}>{children}</div>
    </NextIntlClientProvider>
  );
}
