import { definePlugin } from '/@src/utils/plugins'
import axios from 'axios'
/**
 * Here we are setting up two router navigation guards
 * (note that we can have multiple guards in multiple plugins)
 *
 * We can add meta to pages either by declaring them manualy in the
 * routes declaration (see /@src/router.ts)
 * or by adding a <route> tag into .vue files (see /@src/pages/sidebar/dashboards.ts)
 *
 * <script setup lang="ts">
 * definePage({
 *   meta: {
 *     requiresAuth: true,
 *   },
 * })
 * </script>
 *
 * <template>
 *  // HTML content
 * </template>
 */
export default definePlugin(async ({ router, pinia, event }) => {
  const userSession = useUserSession(pinia)

  // 2. If the page requires auth, check if user is logged in
  // if not, redirect to login page.
  router.beforeEach(async (to,from,next) => {
    try {
      // Do api request call to retreive user profile.
      // Note that the api is provided with json-server
      const user = await axios.get('/api/user/info')
      userSession.setUser(user)
      if (userSession.user.data && to.path === '/') {
        return next('/app/priceManagement')
      }
      return next()
    }catch (err) {
      // Delete stored token if it fails
      userSession.logoutUser()
      if (to.path !== '/') {
        window.location.href = 'https://ep.kospo.co.kr'
        return // 흐름 중단
      }
      return next()
    }
  })
})
