import { createRouter, createWebHistory } from "@ionic/vue-router";
import { RouteRecordRaw } from "vue-router";
import TabsPage from "../views/TabsPage.vue";
import { useUserStore } from "@/store/user";
import http from "@/plugins/http";

const routes: Array<RouteRecordRaw> = [
    {
        path: "/",
        redirect: "/tabs/home",
    },
    {
        path: "/tabs/",
        component: TabsPage,
        children: [
            {
                path: "",
                redirect: "/tabs/home",
            },
            {
                path: "home",
                component: () => import("@/views/HomeTab.vue"),
            },
            {
                path: "forYou",
                component: () => import("@/views/ForYouTab.vue"),
            },
            {
                path: "myList",
                component: () => import("@/views/MyListTab.vue"),
            },
            {
                path: "me",
                component: () => import("@/views/MeTab.vue"),
            },
        ],
    },
    {
        path: "/series/:id",
        component: () => import("@/views/SeriesView.vue"),
    },
    {
        path: "/login",
        component: () => import("@/views/LoginView.vue"),
    },
    {
        path: "/settings",
        component: () => import("@/views/SettingsView.vue"),
    },
    {
        path: "/profile",
        component: () => import("@/views/ProfileView.vue"),
    },
];

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes,
});

router.beforeEach(async (to, from, next) => {
    console.log("route change", to);
    // await new Promise((resolve) => setTimeout(resolve, 3000));
    const { user, setUser } = useUserStore();
    if (!user && to.name !== "login") {
        try {
            const res = await http.get("/users/my");
            setUser(res);
            next();
        } catch (err) {
            const res = await http.get("/users/guest");
            setUser(res.user);
            http.setToken(res.token);
            next();
        }
    } else {
        next();
    }
});

export default router;
