import { redirect } from "next/navigation";

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

function toQueryString(params: Record<string, string | string[] | undefined>): string {
  const query = new URLSearchParams();

  for (const [key, value] of Object.entries(params)) {
    if (Array.isArray(value)) {
      for (const entry of value) {
        query.append(key, entry);
      }
      continue;
    }

    if (typeof value === "string") {
      query.set(key, value);
    }
  }

  return query.toString();
}

export default async function VerifyEmailPage({ searchParams }: VerifyEmailPageProps) {
  const params = await searchParams;
  const query = toQueryString(params);
  const destination = query ? `/api/auth/verify-email?${query}` : "/api/auth/verify-email";

  redirect(destination);
}
