export function buildMaterialReturnFinalPdfViewerHref(input: {
  url: string;
  returnTo?: string;
  title?: string;
  downloadName?: string;
}) {
  const searchParams = new URLSearchParams();
  searchParams.set("url", input.url);

  if (input.returnTo) {
    searchParams.set("returnTo", input.returnTo);
  }

  if (input.title) {
    searchParams.set("title", input.title);
  }

  if (input.downloadName) {
    searchParams.set("downloadName", input.downloadName);
  }

  return `/materiel/restitution/final-pdf?${searchParams.toString()}`;
}

export function appendReturnToParam(href: string, returnTo?: string) {
  if (!returnTo) return href;

  const [base, hash] = href.split("#", 2);
  const [pathname, search = ""] = base.split("?", 2);
  const params = new URLSearchParams(search);
  params.set("returnTo", returnTo);

  const nextHref = `${pathname}?${params.toString()}`;
  return hash ? `${nextHref}#${hash}` : nextHref;
}
