import { createRouter, createWebHistory } from "vue-router";
import { isAdmin, isParent, isSub, isUser } from "@/global/request";
import { sendFailedSwal } from "@/global/swal";
import { introspectToken } from '@/utils/tokenUtils';
import { redirectToSSO } from '@/utils/sso';

// TODO 可能需要判斷權限，不然知道網址大家都能進去
const ASSET_URL = import.meta.env.VITE_ASSET_URL

const routes = [
  { 
    name: "sso-login",
    path: '/sso-login', 
    component: () => import("./components/auth/SSOLogin.vue"), 
  },
  {
    name: "maintain",
    path: "/maintain",
    component: () => import("./components/Maintain.vue"),
    meta: {
      permission: true,
      sidebar: false,
      navbar: false,
      sitemap: false,
      requiresAuth: false,
    }
  },
  {
    path: "/user",
    redirect: "/user/parentIndex",
    children: [
      {
        name: "parentIndex",
        path: "parentIndex",
        component: () => import("./components/pages/user/parent/Index.vue"),
        meta: {
          permission: isAdmin(),
          sidebar: true,
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      },
      {
        name: "subIndex",
        path: "subIndex/:id?",
        component: () => import("./components/pages/user/sub/Index.vue"),
        meta: {
          permission: true,
          sidebar: true,
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      },
      {
        name: "subUserIndex",
        path: "subUserIndex/:id?",
        component: () => import("./components/pages/user/subuser/Index.vue"),
        meta: {
          permission: true,
          sidebar: true,
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      },
    ]
  },
  {
    path: "/activate",
    redirect: "/activate/index",
    children: [
      {
        name: "activateIndex",
        path: "index",
        component: () => import("./components/pages/activate/Index.vue"),
        meta: {
          permission: true,
          sidebar: true,
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      },
      {
        name: "activateMain",
        path: "main/:id?",
        component: () => import("./components/pages/activate/Main.vue"),
        meta: {
          permission: true,
          sidebar: true,
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      },
      {
        name: "activateRecord",
        path: "record/:id?",
        component: () => import("./components/pages/activate/Record.vue"),
        meta: {
          permission: true,
          sidebar: true,
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      },
    ]
  },
  {
    path: "/backend",
    redirect: "/backend/group/index",
    children: [
      {
        name: "groupIndex",
        path: "group/index",
        component: () => import("./components/pages/backend/group/Index.vue"),
        meta: {
          permission: true,
          sidebar: true,
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      },
      {
        name: "adminIndex",
        path: "admin/index",
        component: () => import("./components/pages/backend/admin/Index.vue"),
        meta: {
          permission: true,
          sidebar: true,
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      },
    ]
  },
  {
    path: "/userSubSystem",
    redirect: "/userSubSystem/parentSubSystemIndex",
    children: [
      {
        name: "parentSubSystemIndex",
        path: "parentSubSystemIndex/:subSystemId?",
        component: () => import("./components/pages/userSubSystem/parent/Index.vue"),
        meta: {
          permission: isAdmin(),
          sidebar: true,
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      },
      {
        name: "subSubSystemIndex",
        path: "subSubSystemIndex/:subSystemId?/:id?",
        component: () => import("./components/pages/userSubSystem/sub/Index.vue"),
        meta: {
          permission: true,
          sidebar: true,
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      },
      {
        name: "subUserSubSystemIndex",
        path: "subUserSubSystemIndex/:subSystemId?/:id?",
        component: () => import("./components/pages/userSubSystem/subuser/Index.vue"),
        meta: {
          permission: true,
          sidebar: true,
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      },
    ]
  },
  {
    path: "/news",
    redirect: "/news/index",
    children: [
      {
        name: "newsList",
        path: "list",
        component: () => import("./components/pages/news/List.vue"),
        meta: {
          permission: true,
          sidebar: isAuthenticated(),
          navbar: true,
          sitemap: true,
          requiresAuth: false,
        }
      },
      {
        name: "newsShow",
        path: "show/:id",
        component: () => import("./components/pages/news/Show.vue"),
        meta: {
          permission: true,
          sidebar: isAuthenticated(),
          navbar: true,
          sitemap: true,
          requiresAuth: false,
        }
      },
      {
        name: "newsShowAuth",
        path: "showAuth/:id",
        component: () => import("./components/pages/news/ShowAuth.vue"),
        meta: {
          permission: true,
          sidebar: isAuthenticated(),
          navbar: true,
          sitemap: false,
          requiresAuth: false,
        }
      },
      {
        name: "newsIndex",
        path: "index",
        component: () => import("./components/pages/news/Index.vue"),
        meta: {
          permission: true,
          sidebar: isAuthenticated(),
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      },
    ]
  },
  {
    path: "/home",
    redirect: "/home/parentHome",
    children: [
      {
        name: "adminHome",
        path: "adminHome",
        component: () => import("./components/pages/home/admin/Index.vue"),
        meta: {
          permission: true,
          sidebar: isAuthenticated(),
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      },
      {
        name: "parentHome",
        path: "parentHome",
        component: () => import("./components/pages/home/parent/Index.vue"),
        meta: {
          permission: true,
          sidebar: isAuthenticated(),
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      },
    ]
  },
  {
    path: "/plan",
    redirect: "/plan/index",
    children: [
      {
        name: "planIndex",
        path: "index",
        component: () => import("./components/pages/plan/Index.vue"),
        meta: {
          permission: true,
          sidebar: isAuthenticated(),
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      }
    ]
  },
  {
    path: "/statistics",
    redirect: "/statistics/index",
    children: [
      {
        name: "statisticsIndex",
        path: "index",
        component: () => import("./components/pages/statistics/Index.vue"),
        meta: {
          permission: true,
          sidebar: isAuthenticated(),
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      },
      {
        name: "statisticsDetail",
        path: "detail/:subSystemId/:planId",
        component: () => import("./components/pages/statistics/Detail.vue"),
        meta: {
          permission: true,
          sidebar: isAuthenticated(),
          navbar: true,
          sitemap: false,
          requiresAuth: true,
        }
      }
    ]
  },
];

const router = createRouter({
  history: createWebHistory(ASSET_URL),
  routes
});

router.beforeEach(async (to, from, next) => {
  const sso_token = localStorage.getItem('access_token');
  const api_token = localStorage.getItem('APP_USER_TOKEN');
  if ((!sso_token || !api_token) && !to.fullPath.includes('/sso-login')) {
    redirectToSSO();
    return;
  }

  // 驗證 token 是否有效
  if (sso_token) {
    const isValid = await introspectToken(sso_token);
    console.log("introspect isValid", isValid);
    if (!isValid) {
      localStorage.removeItem('access_token');
      redirectToSSO();
      return;
    }
  }

  // 根據權限前往對應頁面
  if (to.path === '/' && isAuthenticated()) {
    if (isAdmin()) {
      return next({ name: 'adminHome' });
    } else {
      return next({ name: 'parentHome' });
    }
  }

  return next();
});

function isAuthenticated() {
  return Boolean(localStorage.getItem('APP_USER_TOKEN'))
}

export default router