import type { Router } from 'vue-router'
import type { NotificationTarget } from '@/types/api'

export const navigateNotificationTarget = (router: Router, target?: NotificationTarget | null) => {
  if (!target || target.available === false) return false
  const query = target.query
    ? Object.fromEntries(Object.entries(target.query).map(([key, value]) => [key, String(value)]))
    : undefined

  if (target.route_name) {
    if (!router.hasRoute(target.route_name)) return false
    void router.push({
      name: target.route_name,
      params: target.route_params || undefined,
      query
    })
    return true
  }

  const path = target.route_path || ''
  if (!path.startsWith('/') || path.startsWith('//') || /^https?:\/\//i.test(path)) return false

  const resolved = router.resolve({
    path,
    query
  })
  if (!resolved.matched.length || resolved.name === 'Exception404') return false

  void router.push(resolved)
  return true
}
