"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCatalogMetas = getCatalogMetas;
exports.createCatalog = createCatalog;
exports.isValidItemId = isValidItemId;
exports.processMultiStatusErrorResponse = processMultiStatusErrorResponse;
exports.getCatalogNames = getCatalogNames;
exports.getItemKeys = getItemKeys;
async function getCatalogMetas(request, endpoint) {
    const response = await request(`${endpoint}/catalogs`, {
        method: 'get'
    });
    return response?.data?.catalogs;
}
async function createCatalog(request, endpoint, hookInputs) {
    const { created_catalog_name = '', description = '', columns = [] } = hookInputs ?? {};
    const fields = [{ name: 'id', type: 'string' }].concat(columns
        ?.filter((column) => column.name !== 'id')
        .map((column) => ({
        name: column?.name,
        type: column?.type
    })));
    const body = {
        catalogs: [
            {
                name: created_catalog_name,
                description,
                fields
            }
        ]
    };
    try {
        await request(`${endpoint}/catalogs`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            json: body
        });
        return {
            successMessage: 'Catalog created successfully',
            savedData: {
                catalog_name: created_catalog_name
            }
        };
    }
    catch (error) {
        return {
            error: {
                message: (error?.response?.data).errors?.[0]?.message ?? 'Unknown Error',
                code: 'ERROR'
            }
        };
    }
}
function isValidItemId(item_id) {
    return /^[a-zA-Z0-9_-]+$/.test(item_id);
}
function processMultiStatusErrorResponse(response, multiStatusResponse, validPayloadMap, payload) {
    const { errors = [] } = response ?? {};
    let isValidCatalog = true;
    errors?.forEach((error) => {
        const isObject = Array.isArray(error?.parameters) && error.parameters.length > 1;
        if (error?.id !== 'catalog-not-found') {
            error.parameter_values?.forEach((parameter_value) => {
                const itemId = isObject ? parameter_value?.['id'] : parameter_value;
                if (validPayloadMap.has(itemId)) {
                    const index = validPayloadMap.get(itemId);
                    multiStatusResponse.setErrorResponseAtIndex(index, {
                        status: 400,
                        errortype: 'PAYLOAD_VALIDATION_FAILED',
                        errormessage: error.message || 'Unknown error',
                        sent: { ...payload[index]?.item, id: itemId },
                        body: error
                    });
                    validPayloadMap.delete(itemId);
                }
            });
        }
        else {
            isValidCatalog = false;
        }
    });
    if (!isValidCatalog) {
        validPayloadMap.forEach((index, itemId) => {
            multiStatusResponse.setErrorResponseAtIndex(index, {
                status: 404,
                errortype: 'NOT_FOUND',
                errormessage: `Catalog not found. Please create a catalog first.`,
                sent: { ...payload[index]?.item, id: itemId },
                body: JSON.stringify(errors)
            });
        });
        return;
    }
    if (validPayloadMap.size > 0) {
        validPayloadMap.forEach((index, itemId) => {
            multiStatusResponse.setErrorResponseAtIndex(index, {
                status: 500,
                errortype: 'RETRYABLE_ERROR',
                errormessage: `Item with ID ${itemId} could not be processed due to invalid catalog items in the batch request.`,
                sent: { ...payload[index]?.item, id: itemId },
                body: JSON.stringify(errors)
            });
        });
    }
}
async function getCatalogNames(request, { settings }) {
    let choices = [];
    try {
        const catalogs = await getCatalogMetas(request, settings.endpoint);
        if (catalogs?.length) {
            choices = catalogs.map((catalog) => ({
                label: catalog.name,
                value: catalog.name,
                type: 'string',
                description: catalog?.description
            }));
            return {
                choices
            };
        }
        return {
            choices,
            error: {
                message: 'No catalogs found. Please create a catalog first.',
                code: '404'
            }
        };
    }
    catch (err) {
        return {
            choices,
            error: {
                message: 'Unknown error. Please try again later',
                code: '500'
            }
        };
    }
}
async function getItemKeys(request, settings, payload) {
    const catalog_name = payload?.onMappingSave?.outputs?.catalog_name ?? '';
    try {
        const catalogs = await getCatalogMetas(request, settings.endpoint);
        if (!catalogs?.length) {
            return {
                choices: [],
                error: {
                    message: 'No catalogs found. Please create a catalog first.',
                    code: '404'
                }
            };
        }
        const catalog = catalogs?.find((catalog) => catalog.name === catalog_name);
        if (catalog && Array.isArray(catalog.fields)) {
            const choices = catalog.fields
                .map((field) => ({
                label: field.name,
                value: field.name
            }))
                .filter((field) => field.value !== 'id');
            return {
                choices
            };
        }
        return {
            choices: [],
            error: {
                message: `Catalog "${catalog_name}" not found or has no fields.`,
                code: '404'
            }
        };
    }
    catch (error) {
        return {
            choices: [],
            error: {
                message: error,
                code: '500'
            }
        };
    }
}
//# sourceMappingURL=utils.js.map