<template>
  <component :is="type" v-bind="linkProps(to)">
    <slot />
  </component>
</template>

<script setup lang="ts">
import type { RouteLocationRaw } from 'vue-router'
import { isExternal, objectToGetParams } from '@/utils/util'

interface Props {
  to: {
    path: RouteLocationRaw
    query?: Record<string, string>
  }
}
const props = defineProps<Props>()

const isExternalLink = computed(() => {
  return typeof props.to.path === 'string' && isExternal(props.to.path)
})

const type = computed(() => {
  if (isExternalLink.value) {
    return 'a'
  }
  return 'router-link'
})

const linkProps = (to: Props['to']) => {
  if (isExternalLink.value) {
    return {
      href: to.path + (to.query ? `?${objectToGetParams(to.query)}` : ''),
      target: '_blank',
      rel: 'noopener'
    }
  }
  return {
    to: to
  }
}
</script>
