import type { RouteLocationNormalized } from 'vue-router';

import { getAccessToken } from '@/utils/auth';

export function resolveEnterpriseCodeFromLocation() {
  if (typeof window === 'undefined') {
    return '';
  }

  const fromSearch = (
    new URLSearchParams(window.location.search).get('enterpriseCode') ?? ''
  ).trim();
  if (fromSearch) {
    return fromSearch;
  }

  const hash = window.location.hash ?? '';
  const queryIndex = hash.indexOf('?');
  if (queryIndex === -1) {
    return '';
  }

  return (
    new URLSearchParams(hash.slice(queryIndex + 1)).get('enterpriseCode') ?? ''
  ).trim();
}

export function createRouterGuard(to: RouteLocationNormalized) {
  if (to.path === '/error') {
    return true;
  }

  const enterpriseCode = resolveEnterpriseCodeFromLocation();
  if (!enterpriseCode) {
    return {
      path: '/error',
      replace: true,
    };
  }

  const token = getAccessToken(enterpriseCode);

  if (!token) {
    return {
      path: '/error',
      query: { enterpriseCode },
      replace: true,
    };
  }

  return true;
}
