import { canonicalizePublicSectionBarePath } from '~/utils/public-locales'

function normalizeValue(value) {
  if (Array.isArray(value)) {
    return normalizeValue(value[0] || '')
  }

  return String(value || '').trim()
}

export function resolvePrivateFlowToken(route, sectionPath, paramName = 'token') {
  const routeParam = normalizeValue(route?.params?.[paramName])

  if (routeParam) {
    return routeParam
  }

  const queryToken = normalizeValue(route?.query?.token)

  if (queryToken) {
    return queryToken
  }

  const canonicalPath = canonicalizePublicSectionBarePath(route?.path || route?.fullPath || '/')
  const normalizedSectionPath = `/${String(sectionPath || '').trim().replace(/^\/+|\/+$/g, '')}`
  const detailPrefix = `${normalizedSectionPath}/`

  if (!canonicalPath.startsWith(detailPrefix)) {
    return ''
  }

  return normalizeValue(canonicalPath.slice(detailPrefix.length).split('/')[0] || '')
}
