import { Metadata } from "next";
import { getSession, withPageAuthRequired } from "@auth0/nextjs-auth0";
import { redirect, RedirectType } from "next/navigation";
import { createUserServiceClient } from "@/client/client";
import NewUserForm from "@/components/NewUserForm/NewUserForm";

export const metadata: Metadata = {
  title: "New User",
};

export default withPageAuthRequired(async function NewUser() {
  const session = await getSession();
  if (!session) {
    redirect("/api/auth/login", RedirectType.replace);
  }

  const client = createUserServiceClient();
  const { user } = await client.getUser({ subject: session.user["sub"] });
  if (!user) {
    throw new Error("User not found");
  }

  if (user.ibdUsername) {
    // User already has IBD credentials
    redirect("/dashboard", RedirectType.replace);
  }

  return <NewUserForm />;
});
