/* =====================================================
   Helpers (ملحقات لازم)
===================================================== */

/**
 * جایگزین globalMixin.myEncodeQuery
 */
// export function myEncodeQuery(text) {
//   if (!text) return "";
//   return encodeURIComponent(text);
// }

/**
 * پاکسازی کاراکترهای غیرمجاز
 */
export function cleanTextUnpermittedChars(text) {
  if (!text) return "";

  // همان منطق قبلی (اصلاح‌شده برای JS صحیح)
  text = text.replace(/([\x00-\x1F]|\x7F)/g, "");
  return text;
}

/* =====================================================
   Main: utilGetSearchRequest
===================================================== */

export function utilGetSearchRequest(
  index_key,
  textSearch,
  searchTypeKey,
  mode_url = "normal",
  filterPanel = "",
  filterExtended = "",
  offset = 0,
  limit = 10,
  field_collapse = "normal",
  sortKey = "normal",
  domainKey = "all",
  domainSchema = {},
  user_synonyms = {},
  mirror_type = ""
) {
  let _payload = {};
  let domain_label = "";
  let query_string = cleanTextUnpermittedChars(textSearch);

  /* ===== Base URL ===== */
  let baseUrl = repoApi.search.queryNormal;

  if (mode_url === "elp") {
    baseUrl = elpApi.search.elp_base_search;
    baseUrl = baseUrl.replace("{{index_key}}", index_key);
  }
  else if ( mode_url === "elp_db") {
    baseUrl =  elpApi.search.elp_db_search;
    baseUrl = baseUrl.replace("{{index_key}}", index_key);
  }
   else if (mode_url === "elp_voice") {
    baseUrl = elpApi.search.elp_voice_search;
    baseUrl = baseUrl.replace("{{index_key}}", index_key);
  } else if (mode_url === "mirror") {
    baseUrl = repoApi.search.mirror_search;
    baseUrl = baseUrl.replace("{{mirror_type}}", mirror_type);
  }

  /* =====================================================
     Synonym / Vector / Normal
  ===================================================== */

  let sysnonymSearchQuery = "";

  if (!searchTypeKey) searchTypeKey = "normal";

  if (searchTypeKey === "synonym") {
    let newSynonym = {};

    if (user_synonyms) {
      Object.keys(user_synonyms).forEach((key) => {
        if (
          !("isStopWord" in user_synonyms[key] && user_synonyms[key].isStopWord)
        ) {
          newSynonym[key] = user_synonyms[key].value;
          sysnonymSearchQuery += " " + key;
        }
      });
    }

    if (textSearch === "" || textSearch === undefined)
      textSearch = sysnonymSearchQuery;

    if (Object.keys(newSynonym).length) {
      _payload = {
        synonym: newSynonym,
      };
    }
  } else if (searchTypeKey === "vector") {
    /* ===== Vector ===== */
    _payload = {
      text: query_string,
    };
  } else if (!(textSearch === "" || textSearch === undefined)) {
    /* ===== Normal ===== */
    query_string = query_string;

    if (!domainKey) domainKey = "all";

    if (domainKey === "all") {
      if (domainSchema?.type_action) {
        let isNumberInput = /^\d+$/.test(query_string);

        if (isNumberInput && domainSchema.type_action.number) {
          let tag = domainSchema.type_action.number;
          query_string = encodeURIComponent("#") + tag + " " + query_string;
        }
      }
    } else if (domainKey !== "advance") {
      let domainItem = domainSchema?.domain?.find(
        (item) => item.key === domainKey
      );

      if (domainItem) {
        domain_label = domainItem.label;
        query_string =
          encodeURIComponent("#") + domainItem.tag + " " + query_string;
      }
    }
  }

  /* =====================================================
     Filters
  ===================================================== */

  let filterFull = "";

  if (searchTypeKey !== "vector" && query_string) {
    filterFull += "q=" + query_string;
  }

  filterFull += filterPanel + filterExtended;

  if (!filterFull) filterFull = "none";

  /* =====================================================
     URL Replace
  ===================================================== */

  let url = baseUrl;
  const buildName = import.meta.env.VITE_BUILD_NAME;

  url = url.replace("{{appname}}", buildName);
  url = url.replace("{{index_key}}", index_key);
  url = url.replace("{{search_type}}", searchTypeKey);
  url = url.replace("{{sortKey}}", sortKey);
  url = url.replace("{{field_collapse}}", field_collapse);
  url = url.replace("{{offset}}", offset);
  url = url.replace("{{limit}}", limit);
  url = url.replace("{{filter}}", filterFull);

  /* =====================================================
     Payload
  ===================================================== */

  let filters = (filterPanel + filterExtended)
    .split("&")
    .filter((e) => e.length);

  let filters_obj = {};
  filters.forEach((fl) => {
    let fl_items = fl.split("=");
    if (fl_items.length === 2) filters_obj[fl_items[0]] = fl_items[1];
  });

  let payload_full = {
    track_total_hits: true,
    query: query_string,
    search_type: searchTypeKey,
    filters: filters_obj,
    sort: [sortKey],
    from_: offset,
    size: limit,
    collapse_field: field_collapse,
  };

  if (_payload.synonym) {
    payload_full.user_synonyms = _payload.synonym;
  }

  return {
    url,
    payload_full,
    payload: _payload,
    sysnonymSearchQuery,
    domainLabel: domain_label,
  };
}
