"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createResource = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const utils_1 = require("../../utils");
exports.createResource = {
    key: 'createResource',
    category: extensions_core_1.Category.EHR_INTEGRATIONS,
    title: 'Find or create resource',
    description: 'Find or create any FHIR resource in Medplum. Optionally search for existing resources by type and identifier before creating. Supports single resources or FHIR Bundles (transaction/batch) for creating multiple resources atomically.',
    fields: config_1.fields,
    previewable: false,
    dataPoints: config_1.dataPoints,
    onEvent: async ({ payload, onComplete, onError }) => {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        const { fields: input, medplumSdk, } = await (0, utils_1.validateAndCreateSdkClient)({
            fieldsSchema: config_1.FieldsValidationSchema,
            payload,
        });
        try {
            const resourceData = JSON.parse(input.resourceJson);
            const shouldSearch = input.searchResourceType && input.searchIdentifier;
            if (shouldSearch && input.searchResourceType && input.searchIdentifier) {
                const searchParams = {
                    identifier: input.searchIdentifier,
                };
                const searchBundle = await medplumSdk.search(input.searchResourceType, searchParams);
                if (searchBundle.entry && searchBundle.entry.length > 0) {
                    const latestResource = searchBundle.entry[searchBundle.entry.length - 1].resource;
                    if (latestResource) {
                        await onComplete({
                            data_points: {
                                resourceId: (_a = latestResource.id) !== null && _a !== void 0 ? _a : '',
                                resourceType: latestResource.resourceType,
                                wasResourceFound: 'true',
                            },
                        });
                        return;
                    }
                }
            }
            if (resourceData.resourceType === 'Bundle') {
                const result = await medplumSdk.executeBatch(resourceData);
                const resourceIds = (_c = (_b = result.entry) === null || _b === void 0 ? void 0 : _b.map((entry) => {
                    var _a, _b;
                    if ((_a = entry.response) === null || _a === void 0 ? void 0 : _a.location) {
                        const match = entry.response.location.match(/(?:^|\/)([^/]+)\/([^/]+)(?:\/|$)/);
                        return match ? match[2] : undefined;
                    }
                    return (_b = entry.resource) === null || _b === void 0 ? void 0 : _b.id;
                }).filter(Boolean).join(',')) !== null && _c !== void 0 ? _c : '';
                const resourcesCreated = (_e = (_d = result.entry) === null || _d === void 0 ? void 0 : _d.map((entry) => {
                    var _a, _b, _c, _d, _e;
                    let id;
                    let resourceType;
                    let location;
                    if ((_a = entry.response) === null || _a === void 0 ? void 0 : _a.location) {
                        const match = entry.response.location.match(/(?:^|\/)([^/]+)\/([^/]+)(?:\/|$)/);
                        if (match) {
                            resourceType = match[1];
                            id = match[2];
                            location = `${resourceType}/${id}`;
                        }
                    }
                    if (!id && ((_b = entry.resource) === null || _b === void 0 ? void 0 : _b.id)) {
                        id = entry.resource.id;
                    }
                    if (!resourceType && ((_c = entry.resource) === null || _c === void 0 ? void 0 : _c.resourceType)) {
                        resourceType = entry.resource.resourceType;
                    }
                    if (!location && resourceType && id) {
                        location = `${resourceType}/${id}`;
                    }
                    return {
                        id: id !== null && id !== void 0 ? id : '',
                        resourceType: resourceType !== null && resourceType !== void 0 ? resourceType : '',
                        status: (_e = (_d = entry.response) === null || _d === void 0 ? void 0 : _d.status) !== null && _e !== void 0 ? _e : '',
                        location: location !== null && location !== void 0 ? location : '',
                    };
                }).filter((r) => r.id)) !== null && _e !== void 0 ? _e : [];
                await onComplete({
                    data_points: {
                        bundleId: (_f = result.id) !== null && _f !== void 0 ? _f : '',
                        resourceIds,
                        bundleType: (_g = result.type) !== null && _g !== void 0 ? _g : '',
                        resourcesCreated: JSON.stringify(resourcesCreated),
                        wasResourceFound: 'false',
                    },
                });
            }
            else {
                const result = await medplumSdk.createResource(resourceData);
                await onComplete({
                    data_points: {
                        resourceId: (_h = result.id) !== null && _h !== void 0 ? _h : '',
                        resourceType: result.resourceType,
                        wasResourceFound: 'false',
                    },
                });
            }
        }
        catch (error) {
            const err = error;
            await onError({
                events: [
                    {
                        date: new Date().toISOString(),
                        text: { en: `Failed to create resource: ${err.message}` },
                        error: {
                            category: 'SERVER_ERROR',
                            message: err.message,
                        },
                    },
                ],
            });
        }
    },
};
//# sourceMappingURL=createResource.js.map