export function removeMultipleSlashes(pathname: string) {
  return pathname.replaceAll(/\/\/+/g, "/")
}

export function removeTrailingSlash(pathname: string) {
  if (pathname.endsWith("/")) {
    // Remove the trailing slash
    return pathname.slice(0, -1)
  }
  return pathname
}

export function getFormattedUrlQueryParams(
  searchParams: URLSearchParams,
  dataTypes: Record<string, unknown>
) {
  const searchParamsObject: Record<string, unknown> = Array.from(
    searchParams.entries()
  ).reduce<Record<string, unknown>>(
    (acc, [key, value]) => {
      const keys = key.replace(/\]/g, "").split(/\[|\./) // Split keys by '[' or '.'
      keys.reduce((nestedAcc, k, i) => {
        if (i === keys.length - 1) {
          if (dataTypes[k] == "number") {
            ;(nestedAcc as Record<string, unknown>)[k] = Number(value)
          } else if (dataTypes[k] == "boolean") {
            ;(nestedAcc as Record<string, unknown>)[k] =
              value.toLowerCase() === "true"
          } else {
            ;(nestedAcc as Record<string, unknown>)[k] = value
          }
        } else {
          if (!nestedAcc[k]) {
            nestedAcc[k] = isNaN(Number(keys[i + 1])) ? {} : [] // Initialize as object or array
          }
        }
        return nestedAcc[k] as Record<string, unknown>
      }, acc)
      return acc
    },
    {} as Record<string, unknown>
  )
  return searchParamsObject
}
