
import VBase from './vbase.js'

export default async ($env) => {
  // Load i18n
  try {
    const langs = await (await fetch($env.scoped + '/langs.json')).json()
    $env.$i18n.load(langs)
  } catch (e) {
    console.error('Failed to load langs.json', e)
  }

  // Initialize VBase Service
  const vbase = new VBase('vb', $env.scoped); // Relative path
  $env.$vbase = vbase;

  // Wrap Axios: add auth header
  vbase.wrapAxios($env.$axios);

  $env.$axios.interceptors.response.use(function(response) {
    return response?.data
  }, function(error) {
    let data = error.response ? error.response.data : error.response
    return Promise.reject(data?.message || data);
  });

  // Router Guard
  $env.$router.beforeEnter = async (to, from, next) => {
    const isAuth = to.meta && to.meta.auth;
    const roles = to.meta && to.meta.roles; // Array of required roles

    if (isAuth) {
      if (vbase.isExpired()) {
        try {
          await vbase.refresh();
        } catch (e) {
          vbase.logout('/login?redirect=' + encodeURIComponent(to.fullPath));
          return false;
        }
      }

      if (!vbase.user) {
        try {
          await vbase.fetchUser();
        } catch (e) {
          vbase.logout('/login?redirect=' + encodeURIComponent(to.fullPath));
          return false;
        }
      }

      // Role Check
      if (roles && roles.length > 0) {
        const hasRole = roles.some(role => vbase.hasRole(role));
        console.log(roles, hasRole, vbase.user)
        if (!hasRole) {
          // $env.$router.push('/403');
          // return false;
        }
      }
    }

    next();
  };
}
