export default defineNuxtRouteMiddleware(() => {
  const params = new URLSearchParams(window.location.search)
  const afterPayment = params.get('afterPayment')
  const afterManage = params.get('afterManage')
  const afterUpgrade = params.get('afterUpgrade')

  const upgrade = params.get('upgrade')

  const pricing = params.get('pricing')

  if (upgrade) {
    const url = `/#/upgrade?${params.toString()}`

    window.location.href = url

    return
  }

  if (pricing) {
    const workspaceId = params.get('workspaceId')

    const searchParams = new URLSearchParams(params.toString())
    searchParams.delete('workspaceId')

    const url = `/#/${workspaceId}/pricing${searchParams.toString() ? `?${searchParams.toString()}` : ''}`

    window.location.href = url

    return
  }

  if (afterPayment || afterManage || afterUpgrade) {
    const workspaceId = params.get('workspaceId')
    const returnToPage = params.get('returnToPage')

    let url = ''

    if (returnToPage === 'org') {
      url = `/#/admin/${workspaceId}/billing?${params.toString()}`
    } else if (returnToPage === 'account') {
      url = `/#/account/workspace/${workspaceId}/settings?${params.toString()}`
    } else {
      url = `/#/${workspaceId}/settings?tab=billing&${params.toString()}`
    }

    window.location.href = url
  }
})
