"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.startConsolidatedQuery = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const api_sdk_1 = require("@metriport/api-sdk");
const client_1 = require("../../client");
const errorHandler_1 = require("../../shared/errorHandler");
const fields_1 = require("./fields");
const dataPoints_1 = require("./dataPoints");
const zod_1 = require("zod");
const startConsolidatedQuerySchema = zod_1.z.object({
    patientId: zod_1.z
        .string({ errorMap: () => ({ message: 'Missing patientId' }) })
        .min(1),
    resources: zod_1.z.string().optional(),
    dateFrom: zod_1.z.string().optional(),
    dateTo: zod_1.z.string().optional(),
    conversionType: zod_1.z.string().optional(),
});
exports.startConsolidatedQuery = {
    key: 'startConsolidatedQuery',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Start Consolidated Data Query',
    description: "Starts an asynchronous query for the Patient's consolidated FHIR data. Results are sent via webhooks.",
    fields: fields_1.startConsolidatedQueryFields,
    previewable: false,
    dataPoints: dataPoints_1.consolidatedQueryDataPoints,
    onActivityCreated: async (payload, onComplete, onError) => {
        var _a;
        try {
            const { patientId, resources, dateFrom, dateTo, conversionType } = startConsolidatedQuerySchema.parse(payload.fields);
            const api = (0, client_1.createMetriportApi)(payload.settings);
            let resourceTypes;
            if (resources !== undefined && resources.length > 0) {
                const validTypes = new Set(api_sdk_1.resourceTypeForConsolidation);
                resourceTypes = resources
                    .split(',')
                    .map((r) => r.trim())
                    .filter((r) => validTypes.has(r));
            }
            const resp = await api.startConsolidatedQuery(patientId, resourceTypes, dateFrom, dateTo, conversionType);
            await onComplete({
                data_points: {
                    status: resp.status,
                    requestId: (_a = resp.requestId) !== null && _a !== void 0 ? _a : '',
                },
            });
        }
        catch (err) {
            await (0, errorHandler_1.handleErrorMessage)(err, onError);
        }
    },
};
//# sourceMappingURL=startConsolidatedQuery.js.map