import { handleResponseErrors } from "../utilities/apiHelpers.mjs";
import { useLookupsStore } from "../stores/lookupsStore.mjs";
import { executeQueryAdHoc, executeQueryInstance, executeQueryInstanceWithApiMethodInstance, executeQueryWithParameters } from "../udp/utilities/methodUtils.mjs";
import QueryResult from "../models/QueryResult.mjs";
import { useCallback } from "react";
import { cloneDeep } from "lodash-es";
//#region src/hooks/useQueryExecutors.ts
const useQueryExecutors = () => {
	const { lookupApiMethodId, lookupsDataMap, setLookupsDataMap } = useLookupsStore();
	const getLookupById = useCallback((lookupId) => {
		if (!lookupsDataMap || !lookupId) return null;
		return lookupsDataMap[lookupId];
	}, [lookupsDataMap]);
	const getMappedSearchResults = (lookups = {}, searchResults = {
		pageList: [],
		countable: false,
		total: 0,
		eagerLoad: false,
		aggregateResults: [],
		aliasMap: [],
		lookupsMap: []
	}) => {
		const mapLookup = (item) => {
			const updatedItem = { ...item };
			Object.keys(lookups).forEach((attribute) => {
				const lookup = lookups[attribute];
				const propertyValue = item[attribute];
				if (propertyValue !== null && propertyValue !== void 0) {
					const matchingLookupRow = lookup?.data?.find((row) => {
						if (lookup.keyName && row[lookup.keyName]) return row[lookup.keyName].toString() === propertyValue.toString();
						return false;
					});
					if (matchingLookupRow && lookup.valueName) updatedItem[attribute] = matchingLookupRow[lookup.valueName];
				}
			});
			return updatedItem;
		};
		const updatedPageList = searchResults.pageList.map(mapLookup);
		const updatedAggregateResults = searchResults?.aggregateResults?.map?.(mapLookup);
		return {
			...searchResults,
			pageList: updatedPageList,
			aggregateResults: updatedAggregateResults
		};
	};
	const processQueryResponseWithLookups = useCallback(async (lookupApiMethodId_0, response, replaceCache, showSnackbars, lookupDataMap) => {
		let resultData = new QueryResult();
		let lookupsMap = {};
		if (response?.status === 200) {
			lookupsMap = lookupDataMap || response?.data?.lookupsMap || {};
			resultData = response.data;
		} else {
			showSnackbars && handleResponseErrors("Could not retrieve query data");
			return null;
		}
		const promises = [];
		const lookups_0 = {};
		Object.keys(lookupsMap).forEach((key) => {
			const lookupConfig = lookupsMap[key];
			if (lookupConfig?.value) {
				const existingLookup = !replaceCache && getLookupById(lookupConfig.value);
				const lookupQueryData = { id: lookupConfig.value };
				if (!existingLookup) promises.push(executeQueryWithParameters({ data: lookupQueryData }, lookupApiMethodId_0).then((response_0) => {
					if (response_0?.status === 200 && response_0?.data) {
						const lookupConfig_0 = lookupsMap[key];
						lookups_0[key] = {
							data: response_0.data.data,
							keyName: lookupConfig_0.lookupKeyName || response_0.data.keyName,
							valueName: lookupConfig_0.lookupValueName || response_0.data.valueName,
							businessObjectKey: response_0.data.businessObjectKey
						};
						setLookupsDataMap({ [response_0.data.id]: response_0.data }, replaceCache);
					}
				}).catch((e) => e));
				else lookups_0[key] = {
					data: existingLookup.data,
					keyName: lookupConfig.lookupKeyName || existingLookup.keyName,
					valueName: lookupConfig.lookupValueName || existingLookup.valueName,
					businessObjectKey: existingLookup.businessObjectKey
				};
			}
		});
		await Promise.all(promises);
		resultData = getMappedSearchResults(lookups_0, resultData);
		return resultData;
	}, [getLookupById]);
	const executeQueryAdHocAndMapLookups = useCallback(async (searchObject = {}, apiMethodId, lookupsMap_0, replaceCache_0, showSnackbars_0 = false) => {
		if (!lookupApiMethodId) console.info("Udp Lookup Api Method Id NOT Set");
		console.info("Udp Lookup Api Method Id IS Set");
		const response_1 = await executeQueryAdHoc(searchObject || {}, apiMethodId);
		if (lookupApiMethodId) return await processQueryResponseWithLookups(lookupApiMethodId, response_1, replaceCache_0, showSnackbars_0, lookupsMap_0);
		return response_1?.data;
	}, [lookupApiMethodId, processQueryResponseWithLookups]);
	const executeQueryInstanceAndMapLookups = useCallback(async (queryParams = {}, apiMethodInstanceId, replaceCache_1, showSnackbars_1 = false, urlQueryParams = "") => {
		if (!lookupApiMethodId) console.info("Udp Lookup Api Method Id NOT Set");
		console.info("Udp Lookup Api Method Id IS Set");
		const response_2 = await executeQueryInstance({ data: queryParams || {} }, apiMethodInstanceId, urlQueryParams);
		if (lookupApiMethodId) return await processQueryResponseWithLookups(lookupApiMethodId, response_2, replaceCache_1, showSnackbars_1, null);
		return response_2?.data;
	}, [lookupApiMethodId, processQueryResponseWithLookups]);
	const executeQueryInstanceWithObjectAndMapLookups = useCallback(async (queryParams_0 = {}, apiMethodInstance, replaceCache_2, showSnackbars_2 = false, urlQueryParams_0 = "") => {
		if (!lookupApiMethodId) console.info("Udp Lookup Api Method Id NOT Set");
		console.info("Udp Lookup Api Method Id IS Set");
		const response_3 = await executeQueryInstanceWithApiMethodInstance({ data: {
			queryParams: queryParams_0 || {},
			apiMethodInstance
		} }, urlQueryParams_0);
		if (lookupApiMethodId) return await processQueryResponseWithLookups(lookupApiMethodId, response_3, replaceCache_2, showSnackbars_2, null);
		return response_3?.data;
	}, [lookupApiMethodId, processQueryResponseWithLookups]);
	const getLookup = useCallback((lookupId_0) => {
		const cachedLookup = getLookupById(lookupId_0);
		if (cachedLookup) return cachedLookup;
		if (lookupApiMethodId) executeQueryWithParameters({ data: { id: lookupId_0 } }, lookupApiMethodId).then((response_4) => {
			if (response_4?.status === 200 && response_4?.data) return response_4;
		}).catch((e_0) => e_0);
		return null;
	}, [lookupApiMethodId, getLookupById]);
	return {
		executeQueryInstanceAndMapLookups,
		executeQueryInstanceWithObjectAndMapLookups,
		executeQueryAdHocAndMapLookups,
		getCleanData: useCallback((data, lookupsMap_1) => {
			let cleanData = cloneDeep(data);
			if (lookupsMap_1 && cleanData) Object.keys(lookupsMap_1).forEach((attribute_0) => {
				const lookupConfig_1 = lookupsMap_1[attribute_0];
				const lookup_0 = getLookup(lookupConfig_1.value);
				if (Array.isArray(cleanData)) cleanData.forEach((row_0, index) => {
					let currentValue = row_0[attribute_0];
					let temp = lookup_0?.data?.find((item_0) => item_0[lookup_0.valueName] === currentValue);
					if (temp != null) cleanData[index][attribute_0] = temp[lookup_0.keyName];
				});
				else if (cleanData[attribute_0]) {
					let currentValue_0 = cleanData[attribute_0];
					let temp_0 = lookup_0.data.find((item_1) => item_1[lookup_0.valueName] === currentValue_0);
					if (temp_0 != null) cleanData[attribute_0] = temp_0[lookup_0.keyName];
				}
			});
			return cleanData;
		}, [getLookup]),
		getLookup
	};
};
//#endregion
export { useQueryExecutors };

//# sourceMappingURL=useQueryExecutors.mjs.map