import { redirect } from "next/navigation";
import { AuthPageShell } from "@/components/auth-page-shell";
import { LoginPageForm } from "@/components/login-page-form";
import {
  getMailEntryUrlForCurrentRequest,
  getSessionUser,
  redirectToCanonicalMailAuthHostIfNeeded,
} from "@/lib/auth";
import { toSearchString } from "@/lib/mail-urls";

type LoginPageProps = {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
};

function pickParam(value: string | string[] | undefined) {
  return Array.isArray(value) ? value[0] : value;
}

export default async function LoginPage({ searchParams }: LoginPageProps) {
  const params = searchParams ? await searchParams : {};
  await redirectToCanonicalMailAuthHostIfNeeded("/login", toSearchString(params));
  const user = await getSessionUser();
  const error = pickParam(params.error);
  const success = pickParam(params.success);

  if (user) {
    redirect(await getMailEntryUrlForCurrentRequest(user));
  }

  return (
    <AuthPageShell
      title="auth.login.title"
      description="auth.login.description"
    >
      <LoginPageForm error={error} success={success} />
    </AuthPageShell>
  );
}
