import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import {
  getAuthenticatedCachedEntryPath,
  isAuthenticatedToken,
  MARRIAGE_ENTRY_PATH_COOKIE,
} from "@/lib/entry-route-cache";
import {
  getSubmitPath,
  hasCompletedMarriageProfileBasics,
} from "@/lib/get-submit-path";
import { fetchProfileSSR } from "@/lib/ssr-fetch";
import {
  defaultLocale,
  isLocale,
  localizePath,
} from "@/translations/config";

export const dynamic = "force-dynamic";

export default async function RootPage() {
  const cookieStore = await cookies();
  const habibLanguage =
    cookieStore.get("HABIB_LANGUAGE")?.value ??
    cookieStore.get("habib_language")?.value;

  let targetLocale = defaultLocale;

  if (isLocale(habibLanguage)) {
    targetLocale = habibLanguage;
  } else {
    const headersList = await headers();
    const acceptLanguage = headersList.get("accept-language");
    if (acceptLanguage) {
      const preferredLanguage = acceptLanguage.split(",")[0].split("-")[0];
      if (isLocale(preferredLanguage)) {
        targetLocale = preferredLanguage;
      }
    }
  }

  const token =
    cookieStore.get("HABIB_TOKEN")?.value ??
    cookieStore.get("habib_token")?.value;
  const hasToken = isAuthenticatedToken(token);

  if (!hasToken) {
    redirect(`/${targetLocale}`);
  }

  const cachedEntryPath = getAuthenticatedCachedEntryPath(
    token,
    cookieStore.get(MARRIAGE_ENTRY_PATH_COOKIE)?.value,
  );

  if (cachedEntryPath) {
    redirect(localizePath(cachedEntryPath, targetLocale));
  }

  const profile = await fetchProfileSSR(token);
  if (profile) {
    const targetPath = hasCompletedMarriageProfileBasics(profile)
      ? getSubmitPath(profile)
      : "/intro";
    redirect(localizePath(targetPath, targetLocale));
  }

  redirect(`/${targetLocale}`);
}
