"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dynamicFields = void 0;
const properties_1 = require("../../properties");
const constants_1 = require("../constants");
var AssociationCategory;
(function (AssociationCategory) {
    AssociationCategory["HUBSPOT_DEFINED"] = "HUBSPOT_DEFINED";
    AssociationCategory["USER_DEFINED"] = "USER_DEFINED";
    AssociationCategory["INTEGRATOR_DEFINED"] = "INTEGRATOR_DEFINED";
})(AssociationCategory || (AssociationCategory = {}));
exports.dynamicFields = {
    object_details: {
        object_type: async (request) => {
            return await dynamicReadObjectTypes(request);
        },
        id_field_name: async (request, { payload }) => {
            const fromObjectType = payload?.object_details?.object_type;
            if (!fromObjectType) {
                throw new Error("Select a value from the 'Object Type' field");
            }
            return await dynamicReadIdFields(request, fromObjectType);
        },
        property_group: async (request, { payload }) => {
            const fromObjectType = payload?.object_details?.object_type;
            if (!fromObjectType) {
                throw new Error("Select a value from the 'Object Type' field");
            }
            return await dynamicReadPropertyGroups(request, fromObjectType);
        }
    },
    properties: {
        __keys__: async (request, { payload }) => {
            const fromObjectType = payload?.object_details?.object_type;
            if (!fromObjectType) {
                throw new Error("Select a value from the 'Object Type' field");
            }
            return await dynamicReadProperties(request, fromObjectType, false);
        }
    },
    sensitive_properties: {
        __keys__: async (request, { payload }) => {
            const fromObjectType = payload?.object_details?.object_type;
            if (!fromObjectType) {
                throw new Error("Select a value from the 'Object Type' field");
            }
            return await dynamicReadProperties(request, fromObjectType, true);
        }
    },
    associations: {
        object_type: async (request) => {
            return await dynamicReadObjectTypes(request);
        },
        association_label: async (request, { dynamicFieldContext, payload }) => {
            const selectedIndex = dynamicFieldContext?.selectedArrayIndex;
            if (selectedIndex === undefined) {
                throw new Error('Selected array index is missing');
            }
            const fromObjectType = payload?.object_details?.object_type;
            const toObjectType = payload?.associations?.[selectedIndex]?.object_type;
            if (!fromObjectType) {
                throw new Error("Select a value from the from 'Object Type' field");
            }
            if (!toObjectType) {
                throw new Error("Select a value from the 'To Object Type' field");
            }
            return await dynamicReadAssociationLabels(request, fromObjectType, toObjectType);
        },
        id_field_name: async (request, { dynamicFieldContext, payload }) => {
            const selectedIndex = dynamicFieldContext?.selectedArrayIndex;
            if (selectedIndex === undefined) {
                throw new Error('Selected array index is missing');
            }
            const toObjectType = payload?.associations?.[selectedIndex]?.object_type;
            if (!toObjectType) {
                throw new Error("Select a value from the 'To Object Type' field");
            }
            return await dynamicReadIdFields(request, toObjectType);
        }
    },
    dissociations: {
        object_type: async (request) => {
            return await dynamicReadObjectTypes(request);
        },
        association_label: async (request, { dynamicFieldContext, payload }) => {
            const selectedIndex = dynamicFieldContext?.selectedArrayIndex;
            if (selectedIndex === undefined) {
                throw new Error('Selected array index is missing');
            }
            const fromObjectType = payload?.object_details?.object_type;
            const toObjectType = payload?.dissociations?.[selectedIndex]?.object_type;
            if (!fromObjectType) {
                throw new Error("Select a value from the from 'Object Type' field");
            }
            if (!toObjectType) {
                throw new Error("Select a value from the 'To Object Type' field");
            }
            return await dynamicReadAssociationLabels(request, fromObjectType, toObjectType);
        },
        id_field_name: async (request, { dynamicFieldContext, payload }) => {
            const selectedIndex = dynamicFieldContext?.selectedArrayIndex;
            if (selectedIndex === undefined) {
                throw new Error('Selected array index is missing');
            }
            const toObjectType = payload?.dissociations?.[selectedIndex]?.object_type;
            if (!toObjectType) {
                throw new Error("Select a value from the 'To Object Type' field");
            }
            return await dynamicReadIdFields(request, toObjectType);
        }
    },
    list_details: {
        list_name: async (request, { payload }) => {
            const objectType = payload?.object_details?.object_type;
            if (!objectType) {
                throw new Error("Select a value from the 'Object Type' field");
            }
            return await dynamicReadLists(request, objectType);
        }
    }
};
async function dynamicReadIdFields(request, objectType) {
    try {
        const response = await request(`${properties_1.HUBSPOT_BASE_URL}/crm/v3/properties/${objectType}`, {
            method: 'GET',
            skipResponseCloning: true
        });
        return {
            choices: [
                {
                    label: 'Hubspot Record ID (updates only)',
                    value: 'hs_object_id'
                },
                ...(['contact', 'contacts'].includes(objectType)
                    ? [
                        {
                            label: 'email',
                            value: 'email'
                        }
                    ]
                    : []),
                ...response.data.results
                    .filter((field) => field.hasUniqueValue && field.name != 'hs_unique_creation_key')
                    .map((field) => {
                    return {
                        label: field.label,
                        value: field.name
                    };
                })
                    .sort((a, b) => {
                    const labelA = a.label.toLowerCase();
                    const labelB = b.label.toLowerCase();
                    if (labelA < labelB) {
                        return -1;
                    }
                    if (labelA > labelB) {
                        return 1;
                    }
                    return 0;
                })
            ]
        };
    }
    catch (err) {
        const code = err?.response?.status ? String(err.response.status) : '500';
        return {
            choices: [],
            error: {
                message: err?.response?.data?.message ?? 'Unknown error: dynamicReadIdFields',
                code: code
            }
        };
    }
}
async function dynamicReadPropertyGroups(request, objectType) {
    try {
        const response = await request(`${properties_1.HUBSPOT_BASE_URL}/crm/v3/properties/${objectType}/groups`, {
            method: 'GET',
            skipResponseCloning: true
        });
        return {
            choices: response.data.results
                .filter((result) => !result.archived)
                .map((result) => ({
                label: result.label,
                value: result.name
            }))
                .sort((a, b) => {
                const labelA = a.label.toLowerCase();
                const labelB = b.label.toLowerCase();
                if (labelA < labelB) {
                    return -1;
                }
                if (labelA > labelB) {
                    return 1;
                }
                return 0;
            })
        };
    }
    catch (err) {
        const code = err?.response?.status ? String(err.response.status) : '500';
        return {
            choices: [],
            error: {
                message: err?.response?.data?.message ?? 'Unknown error: dynamicReadPropertyGroups',
                code: code
            }
        };
    }
}
async function dynamicReadAssociationLabels(request, fromObjectType, toObjectType) {
    try {
        const response = await request(`${properties_1.HUBSPOT_BASE_URL}/crm/v4/associations/${fromObjectType}/${toObjectType}/labels`, {
            method: 'GET',
            skipResponseCloning: true
        });
        return {
            choices: response?.data?.results
                ?.map((res) => ({
                label: !res.label
                    ? `${fromObjectType} to ${toObjectType} (Default label: typeId ${res.typeId})`
                    : `${fromObjectType} to ${toObjectType} ${res.label}`,
                value: `${res.category}:${res.typeId}`
            }))
                .sort((a, b) => {
                const labelA = a.label.toLowerCase();
                const labelB = b.label.toLowerCase();
                if (labelA < labelB) {
                    return -1;
                }
                if (labelA > labelB) {
                    return 1;
                }
                return 0;
            })
        };
    }
    catch (err) {
        const code = err?.response?.status ? String(err.response.status) : '500';
        return {
            choices: [],
            error: {
                message: err?.response?.data?.message ?? 'Unknown error: dynamicReadAssociationLabels',
                code: code
            }
        };
    }
}
async function dynamicReadObjectTypes(request) {
    try {
        const response = await request(`${properties_1.HUBSPOT_BASE_URL}/crm/v3/schemas?archived=false`, {
            method: 'GET',
            skipResponseCloning: true
        });
        const choices = response.data.results
            .map((schema) => ({
            label: `${schema.labels.plural} (Custom)`,
            value: schema.fullyQualifiedName
        }))
            .sort((a, b) => {
            if (a.label < b.label) {
                return -1;
            }
            if (a.label > b.label) {
                return 1;
            }
            return 0;
        });
        return {
            choices: [...choices, ...constants_1.SUPPORTED_HUBSPOT_OBJECT_TYPES]
        };
    }
    catch (err) {
        const code = err?.response?.status ? String(err.response.status) : '500';
        return {
            choices: [],
            error: {
                message: err?.response?.data?.message ?? 'Unknown error: dynamicReadObjectTypes',
                code: code
            }
        };
    }
}
async function dynamicReadProperties(request, objectType, sensitive) {
    try {
        const url = `${properties_1.HUBSPOT_BASE_URL}/crm/v3/properties/${objectType}${sensitive ? '?dataSensitivity=sensitive' : ''}`;
        const response = await request(url, {
            method: 'GET',
            skipResponseCloning: true
        });
        return {
            choices: [
                ...response.data.results
                    .filter((field) => !field.hasUniqueValue && field.modificationMetadata.readOnlyValue === false)
                    .map((field) => {
                    return {
                        label: `${field.label} - ${field.type}`,
                        value: field.name
                    };
                })
                    .sort((a, b) => {
                    const labelA = a.label.toLowerCase();
                    const labelB = b.label.toLowerCase();
                    if (labelA < labelB) {
                        return -1;
                    }
                    if (labelA > labelB) {
                        return 1;
                    }
                    return 0;
                })
            ]
        };
    }
    catch (err) {
        const code = err?.response?.status ? String(err.response.status) : '500';
        return {
            choices: [],
            error: {
                message: err?.response?.data?.message ?? 'Unknown error: dynamicReadProperties',
                code: code
            }
        };
    }
}
async function dynamicReadLists(request, objectType) {
    let objectTypeId = undefined;
    try {
        objectTypeId = await readObjectSchema(request, objectType);
    }
    catch (err) {
        const code = err?.response?.status ? String(err.response.status) : '500';
        return {
            choices: [],
            error: {
                message: err?.response?.data?.message ?? 'Unknown error: readObjectSchema',
                code: code
            }
        };
    }
    const json = {
        processingTypes: ['MANUAL']
    };
    try {
        const url = `${properties_1.HUBSPOT_BASE_URL}/crm/v3/lists/search`;
        let allLists = [];
        let hasMore = true;
        let offset = undefined;
        while (hasMore) {
            if (offset !== undefined) {
                json.offset = offset;
            }
            const response = await request(url, {
                method: 'POST',
                skipResponseCloning: true,
                json
            });
            allLists = [...allLists, ...response.data.lists];
            hasMore = response.data.hasMore;
            offset = response.data.offset;
        }
        const choices = allLists
            .filter((item) => item.processingType === 'MANUAL' && item.objectTypeId === objectTypeId)
            .map((item) => ({
            label: `${item.name}`,
            value: `${item.name}`
        }));
        return { choices };
    }
    catch (err) {
        const code = err?.response?.status ? String(err.response.status) : '500';
        return {
            choices: [],
            error: {
                message: err?.response?.data?.message ?? 'Unknown error: dynamicReadLists',
                code: code
            }
        };
    }
}
async function readObjectSchema(request, objectType) {
    const url = `${properties_1.HUBSPOT_BASE_URL}/crm/v3/schemas/${objectType}`;
    const response = await request(url, {
        method: 'GET'
    });
    return response.data.objectTypeId;
}
//# sourceMappingURL=dynamic-field-functions.js.map