import "server-only"

import { headers } from "next/headers"

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

import type { Lang } from "@/constants/languages"

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

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

export async function modWebviewLink(url: string, lang: Lang) {
  const searchParams = await 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()}`
  }
}
