import type { NavigationGuardWithThis, RouteLocationNormalized } from 'vue-router'
import { useUserStore } from '@/stores/user'

export const updateLoggedIn: NavigationGuardWithThis<undefined> = (_to) => {
  const loggedIn = getCookieValue('loginStatus') === 'true'
  const userStore = useUserStore()

  userStore.$patch({ loggedIn })
  if (loggedIn && !userStore.email) {
    userStore.fetchUser()
  }
}

export const redirectToLoginIfRequired: NavigationGuardWithThis<undefined> = (to, _from) => {
  const userStore = useUserStore()
  if(loginRequired(to) && !userStore.loggedIn) {
    return `/login?next=${to.fullPath}`
  }
}

export const getCookieValue = (cookieName: string): string => {
  // https://stackoverflow.com/questions/5639346/what-is-the-shortest-function-for-reading-a-cookie-by-name-in-javascript
  const cookieValue = document.cookie.match('(^|[^;]+)\\s*' + cookieName + '\\s*=\\s*([^;]+)')
  if (!cookieValue) {
    return ''
  }
  return cookieValue.pop() || '';
}

const loginRequired = (to: RouteLocationNormalized) => {
  return !to.meta?.public
}
