"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "resolveAppointmentSchedules", {
    enumerable: true,
    get: function() {
        return resolveAppointmentSchedules;
    }
});
const _sequelize = require("sequelize");
const _lodash = require("lodash");
const _constants = require("@tamanu/constants");
const _constants1 = require("./constants");
const _sanitizeRecord = require("./sanitizeRecord");
const resolveAppointmentSchedules = async (AppointmentScheduleModel, changes)=>{
    const relevantChanges = changes.filter((c)=>!c.isDeleted && c.data.cancelledAtDate);
    if (relevantChanges.length === 0) {
        return;
    }
    // Map of incoming generatedUntilDates for each schedule
    const generatedUntilDates = (0, _lodash.mapValues)((0, _lodash.keyBy)(relevantChanges, 'data.id'), 'data.generatedUntilDate');
    const outOfBoundAppointments = await AppointmentScheduleModel.sequelize.query(`
    WITH schedule_generated_until_dates AS (
     SELECT value::date_string AS date, key::uuid AS id from json_each_text(:generatedUntilDates)
    )
    SELECT
      *
    FROM
      appointments
    WHERE
      schedule_id IN (:scheduleIds)
      AND status <> :canceledStatus
    AND
      start_time::date_string > (SELECT date FROM schedule_generated_until_dates WHERE id = schedule_id)
    `, {
        type: _sequelize.QueryTypes.SELECT,
        replacements: {
            canceledStatus: _constants.APPOINTMENT_STATUSES.CANCELLED,
            scheduleIds: Object.keys(generatedUntilDates),
            generatedUntilDates: JSON.stringify(generatedUntilDates)
        }
    });
    if (outOfBoundAppointments.length === 0) {
        return;
    }
    const inserts = outOfBoundAppointments.map((a)=>({
            direction: _constants1.SYNC_SESSION_DIRECTION.INCOMING,
            recordType: 'appointments',
            recordId: a.id,
            isDeleted: true,
            data: (0, _sanitizeRecord.sanitizeRecord)(a)
        }));
    return {
        inserts,
        updates: []
    };
};

//# sourceMappingURL=resolveAppointmentSchedules.js.map