"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPatientInfo = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const extensions_core_2 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const utils_1 = require("../../utils");
const zod_1 = require("zod");
const validation_1 = require("../../validation");
exports.extractPatientInfo = {
    key: 'extractPatientInfo',
    category: extensions_core_2.Category.EHR_INTEGRATIONS,
    title: 'Extract Patient Info',
    description: 'Extracts common fields from a patient object',
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: true,
    onActivityCreated: async (payload, onComplete, onError) => {
        var _a, _b, _c, _d, _e, _f, _g;
        try {
            (0, extensions_core_1.validate)({
                schema: zod_1.z.object({
                    fields: config_1.fieldsValidationSchema,
                }),
                payload,
            });
            const patientData = JSON.parse(payload.fields.patientData);
            const patient = validation_1.patientWithIdSchema.parse(patientData);
            const { firstName, lastName } = patient.name.reduce((acc, name) => {
                var _a, _b;
                if (name.use === 'official') {
                    acc.firstName = name.given.join(' ').trim();
                    acc.lastName = (_b = (_a = name.family) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : '';
                }
                return acc;
            }, { firstName: '', lastName: '' });
            const phone = (_c = (_b = (_a = patient.telecom) === null || _a === void 0 ? void 0 : _a.find((t) => t.system === 'phone' && t.use === 'mobile')) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : (_e = (_d = patient.telecom) === null || _d === void 0 ? void 0 : _d.find((t) => t.system === 'phone')) === null || _e === void 0 ? void 0 : _e.value;
            const email = (_g = (_f = patient.telecom) === null || _f === void 0 ? void 0 : _f.find((t) => t.system === 'email')) === null || _g === void 0 ? void 0 : _g.value;
            const dob = patient.birthDate;
            await onComplete({
                data_points: {
                    patientId: patient.id,
                    firstName,
                    lastName,
                    phone,
                    email,
                    dob,
                },
            });
        }
        catch (error) {
            let parsedError;
            if ((0, utils_1.isZodError)(error)) {
                parsedError = (0, utils_1.parseZodError)(error);
            }
            else {
                parsedError = (0, utils_1.parseUnknowError)(error);
            }
            await onError({
                events: [parsedError],
            });
        }
    },
};
//# sourceMappingURL=extractPatientInfo.js.map