import { Environment } from '@/environments/environment';

/**
 * @description 计算跳转路径是否在白名单中
 * @param {string} url
 * @returns {*}  {boolean}
 */
const isAllowed = (url: string): boolean => {
  if (!url) return false;
  const { protocol, hostname, origin } = new URL(url, window.location.origin);
  // 非http、https、blob:协议直接拦截
  if (!['blob:', 'https:', 'http:'].includes(protocol)) return false;
  // 相对路径直接放过
  if (window.location.origin === origin) {
    return true;
  }
  const allowList: string[] = Environment.redirectWhiteList.split(',');
  return allowList.some(rule => {
    if (typeof rule === 'string') {
      if (rule.includes('*')) {
        const reg = new RegExp(`^${rule.replace(/\*/g, '[^/]+')}$`);
        return reg.test(hostname);
      }
      return rule === `${protocol}//${hostname}`;
    }
    return (rule as RegExp).test(url);
  });
};

/**
 * 唯一重定向出口
 * @param url 目标地址
 * @param fallback 不合法时回退地址，默认当前页
 */
export function safeRedirect(
  url: string,
  options: any = {},
): Window | null | undefined {
  try {
    if (isAllowed(url)) {
      const { type = '_blank' } = options;
      if (type === 'href') {
        window.location.href = url;
      } else {
        return window.open(url, type);
      }
    } else {
      console.error(`重定向路径${url}不在白名单中，请确认是否正确！`);
    }
  } catch {
    console.error(`重定向路径${url}不在白名单中，请确认是否正确！`);
  }
}
