"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.searchPatientsByPatientCode = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const config_1 = require("./config");
const zod_1 = require("zod");
const awellSdk_1 = __importDefault(require("../../sdk/awellSdk"));
const addEventLog_1 = require("../../../../../src/lib/awell/addEventLog");
exports.searchPatientsByPatientCode = {
    key: 'searchPatientsByPatientCode',
    category: extensions_core_1.Category.DEMO,
    title: 'Search patient by patient code (DEPRECATED, USE IDENTIFIERS)',
    description: "Search whether the current patient already exists. Search happens based on the `patient_code` field which is taken from the patient's profile.",
    fields: config_1.fields,
    dataPoints: config_1.dataPoints,
    previewable: false, // We don't have patients in Preview, only cases.
    onEvent: async ({ payload, onComplete, helpers }) => {
        const { patient: { id: patientId, profile: { patient_code }, }, } = (0, extensions_core_1.validate)({
            schema: zod_1.z.object({
                patient: config_1.PatientValidationSchema,
            }),
            payload,
        });
        const awellSdk = await helpers.awellSdk();
        const sdk = new awellSdk_1.default({
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            apiUrl: awellSdk.apiUrl,
            apiKey: awellSdk.apiKey,
        });
        const results = await sdk.searchPatientsByPatientCode({
            patient_code,
        });
        /**
         * When searching for other patients with the same patient code,
         * we need to exclude the current patient from the search results.
         * Otherwise the result would always be true.
         */
        const resultsWithoutCurrentPatient = results.filter((res) => res.id !== patientId);
        const numberOfPatientsFound = resultsWithoutCurrentPatient.length;
        const patientAlreadyExists = numberOfPatientsFound > 0;
        const awellPatientIds = resultsWithoutCurrentPatient
            .map((result) => result.id)
            .join(',');
        await onComplete({
            data_points: {
                patientAlreadyExists: String(patientAlreadyExists),
                numberOfPatientsFound: String(numberOfPatientsFound),
                awellPatientIds,
            },
            events: [
                (0, addEventLog_1.addActivityEventLog)({
                    message: patientAlreadyExists
                        ? `Patient with patient code ${patient_code} already exists. Patient IDs: ${awellPatientIds}`
                        : `Patient with patient code ${patient_code} does not exists yet.`,
                }),
            ],
        });
    },
};
//# sourceMappingURL=searchPatientsByPatientCode.js.map