const env = __VITE_ENV__;

export const API_CONTEXT_CACHE_KEY = "ykt_team_api_context";

export const CORP_API_BASE_URL_MAP = {
  wwa54dfba0b5441ef1: "https://crm.gykqyy.com/ykt/",
};

function normalizeBaseUrl(url) {
  return String(url || "").replace(/\/+$/, "");
}

function getDefaultBaseUrl() {
  return normalizeBaseUrl(env.MP_API_BASE_URL);
}

function readCachedContext() {
  if (typeof uni === "undefined" || typeof uni.getStorageSync !== "function") {
    return null;
  }
  try {
    const cached = uni.getStorageSync(API_CONTEXT_CACHE_KEY);
    if (!cached || typeof cached !== "object" || !cached.baseUrl) return null;
    return {
      corpId: cached.corpId || "",
      baseUrl: normalizeBaseUrl(cached.baseUrl),
    };
  } catch (error) {
    return null;
  }
}

function writeCachedContext(context) {
  if (typeof uni === "undefined" || typeof uni.setStorageSync !== "function") {
    return;
  }
  try {
    uni.setStorageSync(API_CONTEXT_CACHE_KEY, {
      corpId: context.corpId || "",
      baseUrl: normalizeBaseUrl(context.baseUrl),
    });
  } catch (error) {
    // 缓存失败不能阻断接口请求。
  }
}

function createContext(corpId, baseUrl) {
  return {
    corpId: corpId || "",
    baseUrl: normalizeBaseUrl(baseUrl),
  };
}

function safeDecode(value) {
  try {
    return decodeURIComponent(value);
  } catch (error) {
    return value;
  }
}

function parseQueryString(queryString) {
  return String(queryString || "")
    .replace(/^[^?]*\?/, "")
    .split("&")
    .reduce((acc, item) => {
      if (!item) return acc;
      const [key, ...valueParts] = item.split("=");
      if (!key) return acc;
      acc[safeDecode(key)] = safeDecode(valueParts.join("=") || "");
      return acc;
    }, {});
}

export function getCorpIdFromAppOptions(options = {}) {
  const query = options.query || options || {};
  const corpId = query.corpId || query.corpid || query.corp_id;
  if (corpId) return String(corpId).trim();

  if (typeof query.q === "string") {
    const qParams = parseQueryString(safeDecode(query.q));
    const qCorpId = qParams.corpId || qParams.corpid || qParams.corp_id;
    if (qCorpId) return String(qCorpId).trim();
  }

  return "";
}

export function initApiContextFromAppOptions(options = {}) {
  const corpId = getCorpIdFromAppOptions(options);
  if (!corpId) return null;
  return resolveApiContext(corpId);
}

export function resolveApiContext(corpId) {
  const normalizedCorpId = String(corpId || "").trim();

  if (normalizedCorpId) {
    const configuredBaseUrl = CORP_API_BASE_URL_MAP[normalizedCorpId];
    const context = createContext(
      normalizedCorpId,
      configuredBaseUrl || getDefaultBaseUrl()
    );
    writeCachedContext(context);
    return context;
  }

  const cachedContext = readCachedContext();
  if (cachedContext) return cachedContext;

  const context = createContext("", getDefaultBaseUrl());
  writeCachedContext(context);
  return context;
}

export function getApiBaseUrlByCorpId(corpId) {
  return resolveApiContext(corpId).baseUrl;
}

export function getDefaultUploadUrl() {
  return `${getDefaultBaseUrl()}/upload`;
}

export function buildApiUrl(path, corpId) {
  const { baseUrl } = resolveApiContext(corpId);
  const normalizedPath = String(path || "").replace(/^\/+/, "");
  return normalizedPath ? `${baseUrl}/${normalizedPath}` : baseUrl;
}
