var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import { useState, useEffect, useCallback } from 'react';
import { usePromotedLookupMethods } from '../../hooks/usePromotedLookupMethods';
import { usePromotedMethodEntity } from '../../hooks/usePromotedMethodEntity';
import { apiMutate } from '../../utilities/useAxiosMutate';
import { useHandleAxiosSnackbar } from '../../utilities/apiHelpers';
import { ConfigService } from '../../configService';
const resolveMethodId = (methods, key) => {
    var _a;
    return (_a = methods === null || methods === void 0 ? void 0 : methods[key]) === null || _a === void 0 ? void 0 : _a.apiMethodId;
};
const showError = (handleErrorSnackbar, message) => handleErrorSnackbar(null, message, null, null);
export const useLookups = (apiCatalogId, productId) => {
    var _a;
    const [lookups, setLookups] = useState([]);
    const [loading, setLoading] = useState(false);
    const { handleErrorSnackbar } = useHandleAxiosSnackbar();
    const productIdArg = productId != null ? String(productId) : undefined;
    const productIdOrNull = (productId !== null && productId !== void 0 ? productId : null);
    // ── Lookup entity methods ────────────────────────────────────
    const { data: lookupMethods, loading: methodsLoading } = usePromotedLookupMethods(apiCatalogId, productIdArg);
    const getAllMethodId = resolveMethodId(lookupMethods, 'unityBaseGetAllMethod');
    const getDataMethodId = (_a = resolveMethodId(lookupMethods, 'unityBaseGetDataMethod')) !== null && _a !== void 0 ? _a : resolveMethodId(lookupMethods, 'unityBaseGetMethod');
    const createMethodId = resolveMethodId(lookupMethods, 'unityBaseCreateMethod');
    const updateMethodId = resolveMethodId(lookupMethods, 'unityBaseUpdateMethod');
    const deleteMethodId = resolveMethodId(lookupMethods, 'unityBaseDeleteMethod');
    // ── LookupColumn entity methods ──────────────────────────────
    const { data: columnMethods } = usePromotedMethodEntity('UdpLookupColumn', true, apiCatalogId, productIdOrNull);
    const createColumnMethodId = resolveMethodId(columnMethods, 'unityBaseCreateMethod');
    const getAllColumnsMethodId = resolveMethodId(columnMethods, 'unityBaseGetAllMethod');
    const updateColumnMethodId = resolveMethodId(columnMethods, 'unityBaseUpdateMethod');
    const deleteColumnMethodId = resolveMethodId(columnMethods, 'unityBaseDeleteMethod');
    // ── LookupValue entity methods ───────────────────────────────
    const { data: valueMethods } = usePromotedMethodEntity('UdpLookupValue', true, apiCatalogId, productIdOrNull);
    const createValueMethodId = resolveMethodId(valueMethods, 'unityBaseCreateMethod');
    const getAllValuesMethodId = resolveMethodId(valueMethods, 'unityBaseGetAllMethod');
    const updateValueMethodId = resolveMethodId(valueMethods, 'unityBaseUpdateMethod');
    const deleteValueMethodId = resolveMethodId(valueMethods, 'unityBaseDeleteMethod');
    // ── Helper: execute a method ─────────────────────────────────
    const execute = useCallback(async (methodId, data = {}) => {
        var _a;
        if (!methodId)
            return null;
        try {
            const response = (await apiMutate(ConfigService.integrationV1ApiUrl, `apimethod/executeQueryWithParameters/${methodId}`, { method: 'post' }, { data }));
            if ((response === null || response === void 0 ? void 0 : response.status) === 200 || (response === null || response === void 0 ? void 0 : response.status) === 201) {
                return (_a = response.data) !== null && _a !== void 0 ? _a : null;
            }
        }
        catch (_b) {
            return null;
        }
        return null;
    }, []);
    // ── Fetch all lookups ────────────────────────────────────────
    const fetchLookups = useCallback(async () => {
        if (!getAllMethodId)
            return;
        setLoading(true);
        try {
            const data = await execute(getAllMethodId);
            setLookups(data !== null && data !== void 0 ? data : []);
        }
        catch (_a) {
            showError(handleErrorSnackbar, 'Failed to fetch lookups');
        }
        finally {
            setLoading(false);
        }
    }, [getAllMethodId, execute, handleErrorSnackbar]);
    useEffect(() => {
        void fetchLookups();
    }, [fetchLookups]);
    // ── CRUD: Lookup ─────────────────────────────────────────────
    const createLookup = useCallback(async (lookupData) => {
        const result = await execute(createMethodId, { requestBody: lookupData });
        if (!result)
            showError(handleErrorSnackbar, 'Failed to create lookup');
        return result;
    }, [createMethodId, execute, handleErrorSnackbar]);
    const updateLookup = useCallback(async (lookupData) => {
        const { id } = lookupData, rest = __rest(lookupData, ["id"]);
        const result = await execute(updateMethodId, { id, requestBody: rest });
        if (!result)
            showError(handleErrorSnackbar, 'Failed to update lookup');
        return result;
    }, [updateMethodId, execute, handleErrorSnackbar]);
    const deleteLookup = useCallback(async (lookupData) => {
        const result = await execute(deleteMethodId, { id: lookupData.id });
        if (!result)
            showError(handleErrorSnackbar, 'Failed to delete lookup');
        return result;
    }, [deleteMethodId, execute, handleErrorSnackbar]);
    // ── CRUD: LookupColumn ──────────────────────────────────────
    const fetchColumns = useCallback(async () => {
        const result = await execute(getAllColumnsMethodId);
        return result !== null && result !== void 0 ? result : [];
    }, [getAllColumnsMethodId, execute]);
    const createLookupColumn = useCallback(async (columnData) => {
        const result = await execute(createColumnMethodId, { requestBody: columnData });
        if (!result)
            showError(handleErrorSnackbar, 'Failed to create lookup column');
        return result;
    }, [createColumnMethodId, execute, handleErrorSnackbar]);
    const updateLookupColumn = useCallback(async (columnData) => {
        const { id } = columnData, rest = __rest(columnData, ["id"]);
        const result = await execute(updateColumnMethodId, { id, requestBody: rest });
        if (!result)
            showError(handleErrorSnackbar, 'Failed to update lookup column');
        return result;
    }, [updateColumnMethodId, execute, handleErrorSnackbar]);
    const deleteLookupColumn = useCallback(async (columnData) => {
        const result = await execute(deleteColumnMethodId, { id: columnData.id });
        if (!result)
            showError(handleErrorSnackbar, 'Failed to delete lookup column');
        return result;
    }, [deleteColumnMethodId, execute, handleErrorSnackbar]);
    // ── CRUD: LookupValue ───────────────────────────────────────
    const fetchValues = useCallback(async () => {
        const result = await execute(getAllValuesMethodId);
        return result !== null && result !== void 0 ? result : [];
    }, [getAllValuesMethodId, execute]);
    const createLookupValue = useCallback(async (valueData) => {
        const result = await execute(createValueMethodId, { requestBody: valueData });
        if (!result)
            showError(handleErrorSnackbar, 'Failed to create lookup value');
        return result;
    }, [createValueMethodId, execute, handleErrorSnackbar]);
    const updateLookupValue = useCallback(async (valueData) => {
        const { id } = valueData, rest = __rest(valueData, ["id"]);
        const result = await execute(updateValueMethodId, { id, requestBody: rest });
        if (!result)
            showError(handleErrorSnackbar, 'Failed to update lookup value');
        return result;
    }, [updateValueMethodId, execute, handleErrorSnackbar]);
    const deleteLookupValue = useCallback(async (valueData) => {
        const result = await execute(deleteValueMethodId, { id: valueData.id });
        if (!result)
            showError(handleErrorSnackbar, 'Failed to delete lookup value');
        return result;
    }, [deleteValueMethodId, execute, handleErrorSnackbar]);
    // ── Lookup resolution ─────────────────────────────────────────
    /**
     * Fetch a single lookup's full data (rows + keyName/valueName) by ID.
     */
    const fetchLookupData = useCallback(async (lookupId) => {
        return execute(getDataMethodId, { id: lookupId });
    }, [getDataMethodId, execute]);
    /**
     * Resolve a raw value through a lookup.
     * Returns the display value, or the raw value if resolution fails.
     *
     * @param lookupId - The lookup to resolve against
     * @param rawValue - The raw value to look up (matched against keyName)
     * @param overrideKeyName - Optional override for which field to match on
     * @param overrideValueName - Optional override for which field to return
     */
    const resolveLookupValue = useCallback(async (lookupId, rawValue, overrideKeyName, overrideValueName) => {
        if (rawValue == null)
            return rawValue;
        const lookupData = await fetchLookupData(lookupId);
        if (!(lookupData === null || lookupData === void 0 ? void 0 : lookupData.data))
            return rawValue;
        const key = overrideKeyName !== null && overrideKeyName !== void 0 ? overrideKeyName : lookupData.keyName;
        const val = overrideValueName !== null && overrideValueName !== void 0 ? overrideValueName : lookupData.valueName;
        if (!key || !val)
            return rawValue;
        const match = lookupData.data.find((row) => String(row[key]) === String(rawValue));
        return match ? match[val] : rawValue;
    }, [fetchLookupData]);
    // ── Method availability ──────────────────────────────────────
    const methodStatus = {
        lookupCreateAvailable: !!createMethodId,
        lookupUpdateAvailable: !!updateMethodId,
        lookupDeleteAvailable: !!deleteMethodId,
        columnCreateAvailable: !!createColumnMethodId,
        columnUpdateAvailable: !!updateColumnMethodId,
        columnDeleteAvailable: !!deleteColumnMethodId,
        valueCreateAvailable: !!createValueMethodId,
        valueUpdateAvailable: !!updateValueMethodId,
        valueDeleteAvailable: !!deleteValueMethodId,
    };
    return {
        lookups,
        loading: loading || methodsLoading,
        refetch: fetchLookups,
        methodStatus,
        // Lookup CRUD
        createLookup,
        updateLookup,
        deleteLookup,
        // Column CRUD
        fetchColumns,
        createLookupColumn,
        updateLookupColumn,
        deleteLookupColumn,
        // Value CRUD
        fetchValues,
        createLookupValue,
        updateLookupValue,
        deleteLookupValue,
        // Lookup resolution
        fetchLookupData,
        resolveLookupValue,
    };
};
//# sourceMappingURL=useLookups.js.map