"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get parseInvoiceInsurancePlanIds () {
        return parseInvoiceInsurancePlanIds;
    },
    get savePatientInsurancePlans () {
        return savePatientInsurancePlans;
    }
});
const _sequelize = require("sequelize");
const _errors = require("@tamanu/errors");
const parseInvoiceInsurancePlanIds = (rawInsurancePlanIds)=>{
    try {
        if (Array.isArray(rawInsurancePlanIds)) {
            return rawInsurancePlanIds;
        }
        if (rawInsurancePlanIds) {
            return JSON.parse(rawInsurancePlanIds);
        }
    } catch (error) {
        throw new _errors.InvalidParameterError('Invalid insurance plan id');
    }
    return undefined;
};
const savePatientInsurancePlans = async (PatientInvoiceInsurancePlanModel, patientId, invoiceInsurancePlanIds)=>{
    if (invoiceInsurancePlanIds == null) {
        return;
    }
    const existingPlans = await PatientInvoiceInsurancePlanModel.findAll({
        where: {
            patientId
        }
    });
    const desiredPlanIds = new Set(invoiceInsurancePlanIds);
    const activePlanIds = new Set(existingPlans.map((plan)=>plan.invoiceInsurancePlanId));
    const toCreate = invoiceInsurancePlanIds.filter((id)=>!activePlanIds.has(id));
    const toDelete = [
        ...activePlanIds
    ].filter((id)=>!desiredPlanIds.has(id));
    const promises = [];
    if (toCreate.length > 0) {
        promises.push(PatientInvoiceInsurancePlanModel.bulkCreate(toCreate.map((id)=>({
                patientId,
                invoiceInsurancePlanId: id
            }))));
    }
    if (toDelete.length > 0) {
        promises.push(PatientInvoiceInsurancePlanModel.destroy({
            where: {
                patientId,
                invoiceInsurancePlanId: {
                    [_sequelize.Op.in]: toDelete
                }
            }
        }));
    }
    await Promise.all(promises);
};

//# sourceMappingURL=patientInsurancePlans.js.map