<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup
import NavigationBar from './components/NavigationBar.vue';
import { useHub } from './hub';
import { useTheme } from './stores/theme';
import /* * as */structs from '@thriftgen/structs_types';
import /* * as */exceptions from '@thriftgen/exceptions_types';
import { RouteMeta, useRouter } from 'vue-router';
import { AlertType, useAlert } from './stores/alert';
import { useAuth } from './stores/auth';
import { watch } from 'vue';
import { storeToRefs } from 'pinia';

const authRef = storeToRefs(useAuth());
const hub = useHub();
const theme = useTheme();
const themeRef = storeToRefs(theme);
const router = useRouter();

async function fetchProfile() {
  const alert = useAlert();
  const auth = useAuth();

  try {
    const resp = await hub.BizCore.client.getProfile(new structs.GetProfileRequest());
    console.log('get profile', resp);
    auth.setProfile(resp.profile);
    return true;
  } catch (e) {
    console.error('get profile', e);
    if (e instanceof exceptions.CoreServicesException) {
      alert.showContent('Attention', 'Login first', { type: AlertType.Error });
    }
  }
  return false;
}

router.beforeResolve(async (to) => {
  // inherit navigation bar visibility from route meta
  theme.setNavigationBarVisibility(
    to.meta.displayNavigationBar == undefined ? true : to.meta.displayNavigationBar,
  );

  // fetch user profile
  const validProfile = await fetchProfile();
  if (to.meta.requiresAuth) {
    if (!validProfile) return '/login';
  }
  return;
});

// monitor state change of logged in
watch(authRef.isLoggedIn, (loggedIn) => {
  const meta = router.currentRoute.value.meta;
  if (meta.requiresAuth && !loggedIn) {
    router.push('/login');
  }
});

// monitor state change of darh theme
watch(themeRef.isDarkThemeEnabled, (darkTheme) => {
  if (darkTheme) {
    document.documentElement.classList.add('dark-theme');
  } else {
    document.documentElement.classList.remove('dark-theme');
  }
});
</script>
<template>
  <NavigationBar v-if="theme.navigationBarVisibility" />
  <RouterView />
</template>

<style scoped>
/*  */
</style>
