/**
 * Orchestrator boot adapter: JWT, enterprise scope, API base for copied WESP static UI.
 */
(function (global) {
  const cfg = global.__WESP_ORCH__ || {};
  const API_BASE = cfg.apiBase || "/api/v1";

  const AUTH_MAP = {
    "/api/auth/change_credentials": "/api/v1/users/me/password",
  };

  const WESP_API_PREFIXES = [
    "/api/admin/",
    "/api/notifications",
    "/api/updates/",
    "/api/sync/",
    "/api/feed_dispensers",
    "/api/components",
    "/api/recipes",
    "/api/reports",
    "/api/analytics/",
    "/api/feed-quality/",
    "/api/periods",
    "/api/auth/",
  ];

  function readToken() {
    return (global.__WESP_ORCH__ && global.__WESP_ORCH__.accessToken) || "";
  }

  function readEnterpriseId() {
    return (global.__WESP_ORCH__ && global.__WESP_ORCH__.enterpriseId) || "";
  }

  function isExternalUrl(url) {
    return /^https?:\/\//i.test(url);
  }

  function patchUrl(url) {
    if (typeof url !== "string" || isExternalUrl(url)) return url;
    for (const [from, to] of Object.entries(AUTH_MAP)) {
      if (url === from || url.startsWith(from + "?")) {
        return to + url.slice(from.length);
      }
    }
    if (url.startsWith("/api/v1/sync/")) {
      return url;
    }
    for (let i = 0; i < WESP_API_PREFIXES.length; i++) {
      if (url.startsWith(WESP_API_PREFIXES[i])) {
        return url;
      }
    }
    if (url.startsWith("/api/") && !url.startsWith("/api/v1/")) {
      return API_BASE + url.slice(4);
    }
    return url;
  }

  function withAuth(url, init) {
    if (isExternalUrl(url)) {
      return init || {};
    }
    const token = readToken();
    const enterpriseId = readEnterpriseId();
    const headers = new Headers((init && init.headers) || {});
    if (token && !headers.has("Authorization")) {
      headers.set("Authorization", "Bearer " + token);
    }
    if (enterpriseId && !headers.has("X-Enterprise-Id")) {
      headers.set("X-Enterprise-Id", enterpriseId);
    }
    return Object.assign({}, init || {}, { headers });
  }

  function appendEnterpriseQuery(url) {
    if (isExternalUrl(url)) return url;
    const enterpriseId = readEnterpriseId();
    if (!enterpriseId || url.indexOf("enterprise_id=") >= 0) {
      return url;
    }
    const sep = url.indexOf("?") >= 0 ? "&" : "?";
    return url + sep + "enterprise_id=" + encodeURIComponent(enterpriseId);
  }

  const nativeFetch = global.fetch.bind(global);
  global.fetch = function (input, init) {
    if (typeof input === "string") {
      const patched = appendEnterpriseQuery(patchUrl(input));
      return nativeFetch(patched, withAuth(patched, init));
    }
    return nativeFetch(input, withAuth("", init));
  };

  global.WespOrchestratorBoot = {
    apiBase: API_BASE,
    get enterpriseId() {
      return readEnterpriseId();
    },
  };
})(window);
