import { redirect } from "next/navigation";
import type { Lang } from "@/lib/config";

function normalizeRedirectTarget(value?: string): string | null {
  if (!value?.startsWith("/")) {
    return null;
  }

  if (value.startsWith("//")) {
    return null;
  }

  return value;
}

export default function LoginPage({
  params,
  searchParams,
}: {
  params: { lang: Lang };
  searchParams?: {
    redirect?: string;
    redirect_url?: string;
    callbackUrl?: string;
  };
}) {
  const { lang } = params;
  const redirectTarget =
    normalizeRedirectTarget(searchParams?.redirect_url) ||
    normalizeRedirectTarget(searchParams?.callbackUrl) ||
    normalizeRedirectTarget(searchParams?.redirect);

  const target = redirectTarget
    ? `/${lang}/clerk-login?redirect_url=${encodeURIComponent(redirectTarget)}`
    : `/${lang}/clerk-login`;

  redirect(target);
}
