"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "AutoDeleteMedicationRequests", {
    enumerable: true,
    get: function() {
        return AutoDeleteMedicationRequests;
    }
});
const _config = /*#__PURE__*/ _interop_require_default(require("config"));
const _tasks = require("@tamanu/shared/tasks");
const _logging = require("@tamanu/shared/services/logging");
const _sequelize = require("sequelize");
const _sleepAsync = require("@tamanu/utils/sleepAsync");
const _ = require(".");
const _dateTime = require("@tamanu/utils/dateTime");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
let AutoDeleteMedicationRequests = class AutoDeleteMedicationRequests extends _tasks.ScheduledTask {
    getName() {
        return 'AutoDeleteMedicationRequests';
    }
    async run() {
        const { PharmacyOrderPrescription } = this.models;
        // Get the auto-delete timeframe setting (in hours)
        const autoDeleteTimeframeHours = await this.settings.get('medications.dispensing.autoDeleteTimeframeHours') ?? 72;
        const { batchSize, batchSleepAsyncDurationInMilliseconds } = this.config;
        if (!batchSize || !batchSleepAsyncDurationInMilliseconds) {
            throw new _.InvalidConfigError('batchSize and batchSleepAsyncDurationInMilliseconds must be set for AutoDeleteMedicationRequests');
        }
        // Calculate cutoff date (current time - autoDeleteTimeframeHours)
        const cutoffDate = new Date();
        cutoffDate.setHours(cutoffDate.getHours() - autoDeleteTimeframeHours);
        const cutoffDateTime = (0, _dateTime.toDateTimeString)(cutoffDate);
        const query = {
            include: [
                {
                    association: 'pharmacyOrder',
                    attributes: [
                        'id',
                        'date'
                    ],
                    where: {
                        date: {
                            [_sequelize.Op.lt]: cutoffDateTime
                        }
                    },
                    required: true
                }
            ],
            where: {
                // Only delete non-completed prescriptions with no dispenses
                isCompleted: false,
                // Use a subquery to filter for prescriptions with no dispenses at the database level
                [_sequelize.Op.and]: [
                    this.sequelize.literal(`(
            SELECT COUNT(*)
            FROM "medication_dispenses"
            WHERE "medication_dispenses"."pharmacy_order_prescription_id" = "PharmacyOrderPrescription"."id"
            AND "medication_dispenses"."deleted_at" IS NULL
          ) = 0`)
                ]
            }
        };
        // Count total records to process
        const toProcess = await PharmacyOrderPrescription.count(query);
        if (toProcess === 0) {
            _logging.log.info('No medication requests to auto-delete');
            return;
        }
        const batchCount = Math.ceil(toProcess / batchSize);
        _logging.log.info('Running batched auto-deletion of medication requests', {
            recordCount: toProcess,
            batchCount,
            batchSize,
            cutoffDateTime,
            autoDeleteTimeframeHours
        });
        for(let i = 0; i < batchCount; i++){
            // Find medication requests that:
            // 1. Are not deleted
            // 2. Were created before the cutoff date
            // 3. Have no dispenses
            const pharmacyOrderPrescriptionsToProcess = await PharmacyOrderPrescription.findAll({
                ...query,
                attributes: [
                    'id'
                ],
                limit: batchSize
            });
            const idsToDelete = pharmacyOrderPrescriptionsToProcess.map((p)=>p.id);
            if (idsToDelete.length > 0) {
                // Soft delete the medication requests
                await PharmacyOrderPrescription.destroy({
                    where: {
                        id: {
                            [_sequelize.Op.in]: idsToDelete
                        }
                    },
                    individualHooks: true
                });
                _logging.log.info(`Auto-deleted ${idsToDelete.length} medication requests in batch ${i + 1}/${batchCount}`);
            }
            await (0, _sleepAsync.sleepAsync)(batchSleepAsyncDurationInMilliseconds);
        }
        _logging.log.info('Completed auto-deletion of medication requests', {
            totalDeleted: toProcess
        });
    }
    /**
   * @param {import('../ApplicationContext').ApplicationContext} context
   */ constructor(context){
        const conf = _config.default.schedules.autoDeleteMedicationRequests;
        const { schedule, jitterTime, enabled } = conf;
        super(schedule, _logging.log, jitterTime, enabled);
        this.models = context.store.models;
        this.config = conf;
        this.sequelize = context.store.sequelize;
        this.settings = context.settings;
    }
};

//# sourceMappingURL=AutoDeleteMedicationRequests.js.map