"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 afterCreateHook () {
        return afterCreateHook;
    },
    get afterDestroyHook () {
        return afterDestroyHook;
    },
    get afterUpdateHook () {
        return afterUpdateHook;
    }
});
const _constants = require("@tamanu/constants");
const addToInvoice = async (instance)=>{
    const invoiceProduct = await instance.sequelize.models.InvoiceProduct.findOne({
        where: {
            category: _constants.INVOICE_ITEMS_CATEGORIES.PROCEDURE_TYPE,
            sourceRecordId: instance.procedureTypeId
        }
    });
    if (!invoiceProduct) {
        return; // No invoice product configured for this procedure type
    }
    if (!instance.encounterId) {
        return; // No encounter for procedure, so no invoice to add to
    }
    const supervisingClinicianId = instance.physicianId ?? (await instance.sequelize.models.Encounter.findByPk(instance.encounterId, {
        attributes: [
            'examinerId'
        ]
    }))?.examinerId;
    await instance.sequelize.models.Invoice.addItemToInvoice(instance, instance.encounterId, invoiceProduct, supervisingClinicianId ?? undefined);
};
const removeFromInvoice = async (instance)=>{
    if (!instance.encounterId) {
        return; // No encounter for procedure, so no invoice to remove from
    }
    await instance.sequelize.models.Invoice.removeItemFromInvoice(instance, instance.encounterId);
};
const updateInvoiceProductAfterUpdateHook = async (instance)=>{
    const previousValues = instance.previous();
    await instance.sequelize.transaction(async ()=>{
        if (previousValues.procedureTypeId && previousValues.procedureTypeId !== instance.procedureTypeId) {
            // Ensure we remove the item from the invoice first, in case the new procedure type is not invoiceable
            await removeFromInvoice(instance);
        }
        await addToInvoice(instance);
    });
};
const afterCreateHook = async (instance)=>{
    await addToInvoice(instance);
};
const afterUpdateHook = async (instance)=>{
    await updateInvoiceProductAfterUpdateHook(instance);
};
const afterDestroyHook = async (instance)=>{
    await removeFromInvoice(instance);
};

//# sourceMappingURL=hooks.js.map