import { redirect } from "next/navigation";
import { AuthPageShell } from "@/components/auth-page-shell";
import { SignupPageForm } from "@/components/signup-page-form";
import {
  getMailEntryUrlForCurrentRequest,
  getSessionUser,
  redirectToCanonicalMailAuthHostIfNeeded,
} from "@/lib/auth";
import { translate, type TranslationKey } from "@/lib/i18n-dictionaries";
import { resolveRequestLocale } from "@/lib/i18n-server";
import { toSearchString } from "@/lib/mail-urls";

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

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

export default async function SignupPage({ searchParams }: SignupPageProps) {
  const params = searchParams ? await searchParams : {};
  await redirectToCanonicalMailAuthHostIfNeeded(
    "/signup",
    toSearchString(params),
  );
  const user = await getSessionUser();
  const error = pickParam(params.error);
  const locale = await resolveRequestLocale();
  const errorKeys: Record<string, TranslationKey> = {
    "domain-taken": "signup.error.domainTaken",
    "email-exists": "signup.error.emailExists",
    "invalid-domain": "signup.error.domainInvalid",
    "invalid-local-part": "signup.error.localPart",
    "mail-auth": "signup.error.mailAuth",
    "mail-config": "signup.error.mailConfig",
    "mail-domain-exists": "signup.error.mailDomainExists",
    "mail-setup": "signup.error.mailSetup",
    "password-mismatch": "signup.error.passwordMismatch",
    "recovery-email-expired": "signup.error.recoveryExpired",
    "recovery-email-invalid": "signup.error.recoveryInvalid",
    "recovery-email-required": "signup.error.recoveryRequired",
    "recovery-email-unverified": "signup.error.recoveryUnverified",
    required: "signup.error.required",
    "terms-required": "signup.error.termsRequired",
  };
  const errorMessage = error
    ? translate(locale, errorKeys[error] ?? "signup.error.default")
    : null;

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

  return (
    <AuthPageShell
      title="auth.signup.title"
      description="auth.signup.description"
    >
      <SignupPageForm initialErrorMessage={errorMessage} />
    </AuthPageShell>
  );
}
