"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "entireResource", {
    enumerable: true,
    get: function() {
        return entireResource;
    }
});
const _constants = require("@tamanu/constants");
const _resources = require("@tamanu/shared/utils/fhir/resources");
async function entireResource({ payload: { resource }, priority = _constants.JOB_PRIORITIES.DEFAULT }, { log, sequelize, models }) {
    const materialisableResources = (0, _resources.resourcesThatCanDo)(models, _constants.FHIR_INTERACTIONS.INTERNAL.MATERIALISE);
    log.debug('Finding resource by name', {
        resource
    });
    const Resource = materialisableResources.find(({ fhirName })=>fhirName === resource);
    if (!Resource) {
        throw new Error(`FhirRefreshEntireResource: No materialisable resource found for ${resource}`);
    }
    for (const UpstreamModel of Resource.UpstreamModels){
        const total = await UpstreamModel.count();
        log.info('Submitting jobs to refresh entire resource', {
            total,
            resource
        });
        // Manually insert jobs in a single query, rather than using Job.submit(),
        // to save on time and memory (pulling all of upstream's IDs). Also because
        // sequelize can't do streaming queries, so doing it correctly in JS would
        // be a huge pain
        await sequelize.query(`INSERT INTO fhir.jobs (topic, payload, priority)
        SELECT
          $topic::text as topic,
          json_build_object(
            'resource', $resource::text,
            'upstreamId', id
          ) as payload,
          $priority::int as priority
        FROM ${UpstreamModel.tableName}`, {
            bind: {
                topic: _constants.JOB_TOPICS.FHIR.REFRESH.FROM_UPSTREAM,
                resource,
                priority
            }
        });
    }
}

//# sourceMappingURL=entireResource.js.map