import { GET_ORG_COMBO } from 'utils/ApiPathConst';
import * as HttpUtils from 'utils/HttpUtils';

export const getOrgDisplayNames = (option) => {
    if (!option) return { primary: "", secondary: "" };

    const en = option.enCompanyName?.trim() || "";
    const ch = option.chCompanyName?.trim() || "";

    if (en && ch) return { primary: en, secondary: ch };
    if (en) return { primary: en, secondary: "" };
    if (ch) return { primary: ch, secondary: "" };
    return { primary: option.name ?? "", secondary: "" };
};

export const getOrgOptionLabel = (option) => getOrgDisplayNames(option).primary;

const orgSearchFields = (option) => [
    option.name,
    option.label,
    option.brNo,
    option.enCompanyName,
    option.chCompanyName,
];

export const filterOrgComboOptions = (options, state) => {
    const inputValue = state?.inputValue?.trim();
    if (!inputValue) return options;

    const searchStr = inputValue.toLowerCase();
    return options.filter((option) =>
        orgSearchFields(option).some(
            (field) => field != null && String(field).toLowerCase().includes(searchStr)
        )
    );
};

export const fetchOrgCombo = ({ query, id, onSuccess, onFinally }) => {
    const params = {};
    if (id) {
        params.id = id;
    } else if (query?.trim()) {
        params.query = query.trim();
    } else {
        onSuccess?.([]);
        onFinally?.();
        return;
    }

    HttpUtils.get({
        url: GET_ORG_COMBO,
        params,
        onSuccess: (responseData) => {
            onSuccess?.(Array.isArray(responseData) ? responseData : []);
        },
        onFail: () => {
            onSuccess?.([]);
        },
        onError: () => {
            onSuccess?.([]);
        },
        onFinally,
    });
};
