(() => {
  const originalHost = "https://tvttbagljqbkcobruwnl.supabase.co";
  const validateUrl = "https://itf2.lovable.app/api/public/validate-license";
  const originalFetch = globalThis.fetch.bind(globalThis);

  async function readJsonBody(input, init) {
    const body = init && "body" in init ? init.body : undefined;
    if (typeof body === "string") return JSON.parse(body);
    if (body instanceof URLSearchParams) return Object.fromEntries(body.entries());
    if (input instanceof Request) return JSON.parse(await input.clone().text());
    return null;
  }

  globalThis.fetch = async (input, init = {}) => {
    const url = typeof input === "string" ? input : input instanceof Request ? input.url : String(input || "");
    const method = (init.method || (input instanceof Request ? input.method : "GET")).toUpperCase();

    if (method === "POST") {
      try {
        const payload = await readJsonBody(input, init);
        if (payload && typeof payload.license_key === "string") {
          return originalFetch(validateUrl, {
            method: "POST",
            mode: "cors",
            credentials: "omit",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload),
          });
        }
      } catch (error) {
        const isLikelyLicenseRequest =
          url.startsWith(originalHost) ||
          url.includes("supabase.co") ||
          url.includes("license") ||
          url.includes("validate");
        if (!isLikelyLicenseRequest) return originalFetch(input, init);

        return originalFetch(validateUrl, {
          method: "POST",
          mode: "cors",
          credentials: "omit",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ license_key: "", bridge_error: true }),
        });
      }
    }

    return originalFetch(input, init);
  };
})();