import type { RuntimeUrlTargeting } from 'types/runtime';

export const checkUrlTargeting = (urlTargeting: RuntimeUrlTargeting[], url?: string): boolean => {
  const pageUrl = (url || window.location.href).replace(/\/$/, '');

  if (urlTargeting.length === 0) return true;

  for (const { url: targetUrlRaw, condition } of urlTargeting) {
    const targetUrl = targetUrlRaw.replace(/\/$/, '');

    switch (condition) {
      case 'does not contain':
        if (!pageUrl.includes(targetUrl)) return true;
        break;
      case 'matches regex':
        if (testRegex(targetUrl, pageUrl)) return true;
        break;
      case 'starts with':
        if (pageUrl.startsWith(targetUrl)) return true; // ✅ fixed
        break;
      case 'contains':
        if (pageUrl.includes(targetUrl)) return true;
        break;
      case 'ends with':
        if (pageUrl.endsWith(targetUrl)) return true;
        break;
      case 'not equals':
        if (pageUrl !== targetUrl) return true;
        break;
      case 'equals':
        if (pageUrl === targetUrl) return true;
        break;
    }
  }

  return false; // none of them matched
};

export const testRegex = (regexStr: string, url: string): boolean => {
  try {
    return new RegExp(regexStr).test(url);
  } catch {
    return false;
  }
};
