// Patch: redirect SUPER CRM WEB login requests to RapidZap panel endpoint.
// Goal: keep the rest of the app intact, only rewrite the authentication call.

(() => {
  const TARGET = "https://painel.rapid-zap.net/api/login.php";

  // Old panel domains used by original build (can vary by build/whitelabel)
  const OLD_HOSTS = new Set([
    "painel.waclientes.com.br",
    "painel.wascript.com.br",
    "painel.wawebhook.com.br",
    "painel.webhook-automation.com.br",
  ]);

  function shouldRewrite(urlStr) {
    try {
      const u = new URL(urlStr, location.href);
      if (!OLD_HOSTS.has(u.host)) return false;
      // rewrite only auth endpoints to avoid breaking other APIs
      const p = (u.pathname || "").toLowerCase();
      const q = (u.search || "").toLowerCase();
      return p.includes("login") || q.includes("login") || p.includes("auth");
    } catch {
      return false;
    }
  }

  function rewrite(urlStr) {
    return TARGET;
  }

  // --- patch fetch ---
  const _fetch = window.fetch.bind(window);
  window.fetch = async (input, init) => {
    try {
      if (typeof input === "string") {
        if (shouldRewrite(input)) {
          return _fetch(rewrite(input), init);
        }
      } else if (input && typeof input === "object" && "url" in input) {
        // Request object
        const req = input;
        if (shouldRewrite(req.url)) {
          const newReq = new Request(rewrite(req.url), req);
          return _fetch(newReq, init);
        }
      }
    } catch {
      // fallthrough
    }
    return _fetch(input, init);
  };

  // --- patch XHR ---
  const _open = XMLHttpRequest.prototype.open;
  XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
    try {
      if (typeof url === "string" && shouldRewrite(url)) {
        url = rewrite(url);
      }
    } catch {
      // ignore
    }
    return _open.call(this, method, url, async, user, password);
  };

  // small marker for debugging
  try {
    // eslint-disable-next-line no-undef
    console.log("[RapidZap] patch-login loaded (rewrite login -> /api/login.php)");
  } catch {}
})();
