"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "setFhirRefreshTriggers", {
    enumerable: true,
    get: function() {
        return setFhirRefreshTriggers;
    }
});
const _database = require("@tamanu/database");
const _resources = require("@tamanu/shared/utils/fhir/resources");
const _logging = require("@tamanu/shared/services/logging");
const _constants = require("@tamanu/constants");
const _config = /*#__PURE__*/ _interop_require_default(require("config"));
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const setFhirRefreshTriggers = async (sequelize)=>{
    const fhirEnabled = !!_config.default?.integrations?.fhir?.enabled;
    const fhirWorkerEnabled = !!_config.default?.integrations?.fhir?.worker?.enabled;
    const triggersEnabled = fhirEnabled && fhirWorkerEnabled;
    // add fhir_refresh trigger to upstream tables of enabled fhir resources
    const materialisableResources = (0, _resources.resourcesThatCanDo)(Object.values(sequelize.models), _constants.FHIR_INTERACTIONS.INTERNAL.MATERIALISE);
    const allUpstreams = Array.from(new Set(materialisableResources.flatMap((resource)=>resource.upstreams?.map((upstream)=>upstream.tableName) || [])));
    await sequelize.transaction(async ()=>{
        for (const { schema, table } of (await (0, _database.tablesWithoutTrigger)(sequelize, 'fhir_refresh_', ''))){
            if (!triggersEnabled || schema !== 'public' || !allUpstreams.includes(table)) {
                continue;
            }
            _logging.log.info(`Adding fhir_refresh trigger to ${schema}.${table}`);
            await sequelize.query(`
          CREATE TRIGGER fhir_refresh_${table}
          AFTER INSERT OR UPDATE OR DELETE ON "${schema}"."${table}" FOR EACH ROW
          EXECUTE FUNCTION fhir.refresh_trigger();
      `);
        }
        for (const { schema, table } of (await (0, _database.tablesWithTrigger)(sequelize, 'fhir_refresh_', ''))){
            if (!triggersEnabled || schema === 'public' && !allUpstreams.includes(table)) {
                _logging.log.info(`Removing fhir_refresh trigger from ${schema}.${table}`);
                await sequelize.query(`
          DROP TRIGGER IF EXISTS fhir_refresh_${table} ON "${schema}"."${table}";
      `);
            }
        }
    });
};

//# sourceMappingURL=setFhirRefreshTriggers.js.map