"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "PlannedMoveTimeout", {
    enumerable: true,
    get: function() {
        return PlannedMoveTimeout;
    }
});
const _config = /*#__PURE__*/ _interop_require_default(require("config"));
const _datefns = require("date-fns");
const _sequelize = require("sequelize");
const _tasks = require("@tamanu/shared/tasks");
const _logging = require("@tamanu/shared/services/logging");
const _sleepAsync = require("@tamanu/utils/sleepAsync");
const _primaryDateTime = require("@tamanu/shared/utils/primaryDateTime");
const _ = require(".");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
let PlannedMoveTimeout = class PlannedMoveTimeout extends _tasks.ScheduledTask {
    getName() {
        return 'PlannedMoveTimeout';
    }
    async run() {
        const { Encounter, Location } = this.models;
        const query = {
            where: {
                plannedLocationStartTime: {
                    [_sequelize.Op.lt]: (0, _primaryDateTime.toPrimaryDateTimeString)((0, _datefns.subHours)(new Date(), this.config.timeoutHours))
                }
            },
            include: [
                {
                    model: Location,
                    as: 'plannedLocation',
                    required: true
                }
            ]
        };
        const toProcess = await Encounter.count(query);
        if (toProcess === 0) return;
        const { batchSize, batchSleepAsyncDurationInMilliseconds } = this.config;
        // Make sure these exist, else they will prevent the script from working
        if (!batchSize || !batchSleepAsyncDurationInMilliseconds) {
            throw new _.InvalidConfigError('batchSize and batchSleepAsyncDurationInMilliseconds must be set for PlannedMoveTimeout');
        }
        const batchCount = Math.ceil(toProcess / batchSize);
        _logging.log.info('Running batched timeout of encounter planned moves', {
            recordCount: toProcess,
            batchCount,
            batchSize
        });
        for(let i = 0; i < batchCount; i++){
            const encounters = await Encounter.findAll({
                ...query,
                limit: batchSize
            });
            for (const encounter of encounters){
                await encounter.addSystemNote(`Automatically cancelled planned move to ${encounter.plannedLocation.name} after ${this.config.timeoutHours} hours`, (0, _primaryDateTime.getCurrentPrimaryTimeZoneDateTimeString)());
                await encounter.update({
                    plannedLocationId: null,
                    plannedLocationStartTime: null
                });
                _logging.log.info('Encounter planned move timeout', {
                    encounterId: encounter.id
                });
            }
            await (0, _sleepAsync.sleepAsync)(batchSleepAsyncDurationInMilliseconds);
        }
    }
    constructor(context, overrideConfig = null){
        const conf = {
            ..._config.default.schedules.plannedMoveTimeout,
            ...overrideConfig
        };
        const { schedule, jitterTime, enabled } = conf;
        super(schedule, _logging.log, jitterTime, enabled);
        this.config = conf;
        this.models = context.store.models;
        // Run once of startup (in case the server was down when it was scheduled)
        if (!conf.suppressInitialRun) {
            this.runImmediately();
        }
    }
};

//# sourceMappingURL=PlannedMoveTimeout.js.map