import { computed } from "vue";
import { union } from "lodash-es";
export function useLookupListMaster(props) {
  const computedModelName = computed(() => {
    let operation = "masterItemByGroupKey";
    if (props.filterText) operation = "masterItemByGroupKeyAndFilterText";
    if (props.itemCodes && props.itemCodes.length > 0) operation = "masterItemByGroupKeyAndItemCodeIn";
    if (props.meilisearch) operation = "masterItemByGroupKeyAndFilterTextAndKeyword";
    if (props.waitForFilter && !props.filterText) operation = "";
    return operation;
  });
  const computedModelBy = computed(() => {
    const modelBy = { groupKey: props.groupKey };
    if (props.filterText) modelBy["filterText"] = props.filterText;
    if (props.itemCodes && props.itemCodes.length > 0) modelBy["itemCodes"] = props.itemCodes;
    return modelBy;
  });
  const computedModelSelectedItemBy = computed(() => ({ groupKey: props.groupKey }));
  const itemTitleField = computed(() => props.lang === "TH" ? "itemValue" : "itemValueAlternative");
  const computedFields = computed(() => {
    const extra = [];
    if (props.filterText) extra.push("filterText");
    if (props.meilisearch) extra.push("_formatted");
    const statusField = props.statusField ?? "statusCode";
    const includeStatus = (props.hideInactiveInList ?? true) && statusField;
    return union(
      ["itemCode", "itemValue", "itemValueAlternative"],
      includeStatus ? [statusField] : [],
      extra,
      props.fields || []
    );
  });
  const formatItemTitle = (item) => {
    const raw = item?.raw ?? item ?? {};
    const resolvedTitle = item?.title || raw?.[itemTitleField.value] || raw?.itemValue || raw?.itemCode;
    if (props.meilisearch) {
      const formatted = raw?._formatted ?? {};
      const code = formatted?.itemCode ?? raw?.itemCode;
      const title = formatted?.[itemTitleField.value] || formatted?.itemValue || formatted?.itemCode || resolvedTitle;
      return (props.showCode ? (code ?? "") + "-" : "") + (title ?? "");
    } else {
      return (props.showCode ? (raw?.itemCode ?? "") + "-" : "") + (resolvedTitle ?? "");
    }
  };
  const computedNoDataText = computed(() => {
    if (props.waitForFilter && !props.filterText) return props.waitForFilterText;
    return props.noDataText;
  });
  const computedSortBy = computed(() => {
    if ((props.sortBy ?? "itemValue") === "itemValue") {
      if (props.showCode) return ["itemCode"];
      return [itemTitleField.value, "itemValue", "itemCode"];
    }
    return [props.sortBy ?? "itemValue"];
  });
  return {
    computedModelName,
    computedModelBy,
    computedModelSelectedItemBy,
    computedFields,
    itemTitleField,
    computedNoDataText,
    computedSortBy,
    formatItemTitle
  };
}
