import "server-only"

import { headers } from "next/headers"

import { Lang } from "@/constants/languages"
import { webviews } from "@/constants/routes/webviews"

export function webviewSearchParams() {
  const searchParams = new URLSearchParams()
  const loginType = headers().get("loginType")
  if (loginType) {
    searchParams.set("loginType", loginType)
  }

  const adobeMc = headers().get("adobe_mc")
  if (adobeMc) {
    searchParams.set("adobe_mc", adobeMc)
  }
  return searchParams
}

export function modWebviewLink(url: string, lang: Lang) {
  const searchParams = webviewSearchParams()
  const urlWithoutLang = url.replace(`/${lang}`, "")

  const webviewUrl = `/${lang}/webview${urlWithoutLang}`
  if (webviews.includes(webviewUrl) || url.startsWith("/webview")) {
    return `${webviewUrl}?${searchParams.toString()}`
  } else {
    return `${url}?${searchParams.toString()}`
  }
}
