import { preferences } from '@vben/preferences';

const LEGACY_HOME_PATTERNS = [
  /^\/app\/[^/]+\/form-render\//,
  /^\/form-render\//,
  /^\/online-dev(?:\/|$)/,
  /^\/online-development(?:\/|$)/,
];

function decodePath(path: string) {
  try {
    return decodeURIComponent(path);
  } catch {
    return path;
  }
}

function isLegacyHomePath(path: string) {
  return LEGACY_HOME_PATTERNS.some((pattern) => pattern.test(path));
}

function normalizeHomePath(path?: null | string) {
  if (!path) {
    return preferences.app.defaultHomePath;
  }

  const decodedPath = decodePath(path);
  return isLegacyHomePath(decodedPath)
    ? preferences.app.defaultHomePath
    : decodedPath;
}

export { normalizeHomePath };
