"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "resolveDuplicatedPatientDisplayIds", {
    enumerable: true,
    get: function() {
        return resolveDuplicatedPatientDisplayIds;
    }
});
const _sequelize = require("sequelize");
const _constants = require("./constants");
const _sanitizeRecord = require("./sanitizeRecord");
const resolveDuplicatedPatientDisplayIds = async (PatientModel, changes)=>{
    const nonDeletedChanges = changes.filter((c)=>!c.isDeleted);
    const patientDisplayIds = nonDeletedChanges.map((c)=>c.data.displayId);
    const patientIds = nonDeletedChanges.map((c)=>c.data.id);
    // Find existing patients that have the same displayIDs and are not the same with the incoming patients
    const existingPatientsWithDuplicatedDisplayIds = await PatientModel.findAll({
        where: {
            displayId: {
                [_sequelize.Op.in]: patientDisplayIds
            },
            id: {
                [_sequelize.Op.notIn]: patientIds
            }
        },
        raw: true
    });
    const existingDisplayIds = existingPatientsWithDuplicatedDisplayIds.map((p)=>p.displayId);
    const duplicatedDisplayIds = patientDisplayIds.filter((displayId)=>existingDisplayIds.includes(displayId));
    if (duplicatedDisplayIds.length > 0) {
        // Create a new incoming snapshot change for the existing patient's display ID and append '_duplicate_1'
        const updatedExistingPatientSnapshotRecords = existingPatientsWithDuplicatedDisplayIds.map((r)=>({
                direction: _constants.SYNC_SESSION_DIRECTION.INCOMING,
                isDeleted: !!r.deletedAt,
                recordType: PatientModel.tableName,
                recordId: r.id,
                data: {
                    ...(0, _sanitizeRecord.sanitizeRecord)(r),
                    displayId: `${r.displayId}_duplicate_1`
                }
            }));
        // Update the to-be-synced patient's display ID to append '_duplicate_2'
        const updatedIncomingPatientSnapshotRecords = changes.filter((c)=>!c.isDeleted && duplicatedDisplayIds.includes(c.data.displayId)).map((c)=>({
                ...c,
                data: {
                    ...c.data,
                    displayId: `${c.data.displayId}_duplicate_2`
                }
            }));
        return {
            inserts: updatedExistingPatientSnapshotRecords,
            updates: updatedIncomingPatientSnapshotRecords
        };
    }
};

//# sourceMappingURL=resolveDuplicatedPatientDisplayIds.js.map