<script setup>
const router = useRouter()
const route = useRoute()
const tabs = useTabs()

definePageMeta({
  middleware: ['auth', 'org']
})

const goTo = (toPath, pathName) => {
  tabs.value.map(item => {
    item.active = false
    return item
  })
  if(tabs.value.filter(i => i.link === '/partners/partners').length >= 1) {
    const tabIndex = tabs.value.findIndex(i => i.link === '/partners/partners')
    tabs.value[tabIndex].active = true
    router.push(toPath)
  } else {
    tabs.value.push({link: '/partners/partners', text: pathName, active: true})
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  }
  //location.href = toPath
}

const retrieve = async () => {
  const res = await $fetch('/api/partners/phonesearch/'+route.params.number, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res?.records) {
    if(Number(res.records.length) >= 1) {
      goTo('/partners/partners/'+res.records[0].C_BPartner_ID.id+'/edit', 'Partners')
    } else {
      goTo('/partners/partners/create', 'Partners')
    }
  }
}
onMounted(retrieve)
</script>

<template>
  <Head>
    <Title>Partner Redirect</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <div>Processing to redirect toward edit page</div>
  </NuxtLayout>
</template>