import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import ListOfArticles from '~src/admin/views/ListOfArticles.vue';
import Schedules from '~src/admin/views/Schedules.vue';
import Settings from '~src/admin/views/Settings.vue';
import Upgrade from '~src/admin/views/Upgrade.vue';
import CreateAccount from '~src/admin/views/CreateAccount.vue';
import AddSchedule from '~src/admin/views/AddSchedule.vue';
import AddArticles from '~src/admin/views/AddArticles.vue';
import MissingApiKey from '~src/admin/views/MissingApiKey.vue';
import { AppConfigType } from '../types';

// @ts-ignore
const settings = boostsite_ai_config_admin as AppConfigType;

// Set correct defualt component based on if user is logged in and has a schedule
const isLoggedIn = settings.is_logged_in;
const hasPlugin = settings.settings.has_plugin;
const schedules = settings.settings.schedules;
const isApiKeyMissing = settings.is_api_key_missing;

// Check if the usser account is expired
const isExpired = !!settings.settings.account_expired;

// Set the component
let rootComponent = ListOfArticles;

if (!isLoggedIn) {
    rootComponent = CreateAccount;
} else if (isApiKeyMissing) {
    rootComponent = MissingApiKey;
} else if (!hasPlugin || schedules.length === 0) {
    rootComponent = AddSchedule;
}

const routes: RouteRecordRaw[] = [
    { path: '/', component: rootComponent },
    { path: '/articles', component: ListOfArticles },
    { path: '/schedules', component: Schedules },
    { path: '/settings', component: Settings },
    { path: '/upgrade', component: Upgrade },
    { path: '/add-articles', component: AddArticles },
    { path: '/add-schedule', component: AddSchedule },
];

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

const isAccountFree = settings.settings.account_type === 'FREE';

router.beforeEach((to, from, next) => {
    // Hide submenu
    if (to.path === '/upgrade' || to.path === '/add-articles' || to.path === '/reset-token') {
        document.body.classList.add('hide-submenu');
    } else {
        document.body.classList.remove('hide-submenu');
    }

    if (!isLoggedIn && to.path !== '/') {
        // Redirect to root if not logged in
        next('/');
    } else if (isApiKeyMissing && to.path !== '/') {
        // Redirect to missing api key if api key is missing
        next('/');
    } else if ((!schedules || !hasPlugin) && to.path !== '/') {
        // Redirect to root if has no schedule
        next('/');
    } else if (isLoggedIn && to.path === '/upgrade' && !isAccountFree) {
        // Redirect to root if paid plan on upgrade
        next('/');
    } else if (isLoggedIn && to.path === '/add-articles' && isAccountFree) {
        // Redirect to root if free plan on add articles
        next('/');
    }

    if (isExpired && (to.path === '/add-articles' || to.path === '/add-schedule')) {
        // Redirect to root if account expired
        next('/');
    }

    next();
});

export default router;
