import { cookies } from "next/dist/client/components/headers";
import styles from "@/app/page.module.css";
import RegisterForm from "./RegisterForm";
import { redirect, useRouter } from "next/navigation";
import { ensureJpg } from "@/image";
import { ValidAuthProvider } from "@/auth/AuthProvider";

function avatarUrlSource(url: URL): ValidAuthProvider | null {
  if (
    url.hostname === "cdn.discordapp.com" &&
    url.pathname.startsWith("/avatars")
  ) {
    return "Discord";
  }

  if (url.hostname === "avatars.githubusercontent.com") {
    return "GitHub";
  }

  return null;
}

export default async function Page({
  searchParams
}: {
  searchParams: {
    displayName?: string;
    email?: string;
    avatar?: string;
  };
}) {
  const cookieStore = cookies();
  const ticket = cookieStore.get("ticket");

  if (ticket === null) {
    redirect("/");
  }

  let initialAvatarBase64 = undefined;
  let avatarSource = null;
  if (searchParams.avatar != null && searchParams.avatar !== "") {
    const url = new URL(searchParams.avatar);
    let tempAvatarSource = avatarUrlSource(url);

    // prevent people from getting the server to fetch() arbitrary URLs
    if (tempAvatarSource == null) {
      return <p>fuck off</p>;
    }

    const req = await fetch(searchParams.avatar);
    const blob = await req.blob();
    const arrayBuffer = await blob.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer);
    if (buffer.length <= 2_000_000) {
      // I hope you are doing well, you deserve the best of luck while working on this project -Ari
      try {
        const jpg = await ensureJpg(buffer);
        initialAvatarBase64 = "data:image/jpeg;base64," + jpg;
        avatarSource = tempAvatarSource;
      } catch (e) {
        console.error(e);
      }
    }
  }

  return (
    <main className={styles.main}>
      <RegisterForm
        initialDisplayName={searchParams.displayName}
        initialEmail={searchParams.email}
        initialAvatarBase64={initialAvatarBase64}
        avatarSource={avatarSource}
      />
    </main>
  );
}
