"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "StaleSyncSessionCleaner", {
    enumerable: true,
    get: function() {
        return StaleSyncSessionCleaner;
    }
});
const _config = /*#__PURE__*/ _interop_require_default(require("config"));
const _sequelize = require("sequelize");
const _tasks = require("@tamanu/shared/tasks");
const _logging = require("@tamanu/shared/services/logging");
const _sync = require("@tamanu/database/sync");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
let StaleSyncSessionCleaner = class StaleSyncSessionCleaner extends _tasks.ScheduledTask {
    getName() {
        return 'StaleSyncSessionCleaner';
    }
    getWhere() {
        const { staleSessionSeconds } = this.config;
        return {
            lastConnectionTime: {
                [_sequelize.Op.lt]: Date.now() - staleSessionSeconds * 1000
            },
            completedAt: {
                [_sequelize.Op.is]: null
            }
        };
    }
    async countQueue() {
        const { SyncSession } = this.store.models;
        return SyncSession.count({
            where: this.getWhere()
        });
    }
    async run() {
        const { SyncSession } = this.store.models;
        const staleSessions = await SyncSession.findAll({
            where: this.getWhere(),
            select: [
                'id'
            ],
            raw: true
        });
        for (const session of staleSessions){
            await (0, _sync.completeSyncSession)(this.store, session.id, 'Session marked as completed due to inactivity');
            const durationMs = Date.now() - session.startTime;
            _logging.log.info('StaleSyncSessionCleaner.closedStaleSession', {
                sessionId: session.id,
                durationMs,
                facilityIds: session.parameters.facilityIds,
                deviceId: session.parameters.deviceId
            });
        }
    }
    constructor(context){
        const conf = _config.default.schedules.staleSyncSessionCleaner;
        const { schedule, jitterTime, enabled } = conf;
        super(schedule, _logging.log, jitterTime, enabled);
        this.config = conf;
        this.store = context.store;
    }
};

//# sourceMappingURL=StaleSyncSessionCleaner.js.map