"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "RemoveDuplicatedDischarges", {
    enumerable: true,
    get: function() {
        return RemoveDuplicatedDischarges;
    }
});
const _dataMigrations = require("@tamanu/database/dataMigrations");
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
let RemoveDuplicatedDischarges = class RemoveDuplicatedDischarges extends _dataMigrations.CursorDataMigration {
    async getQuery() {
        return `
      WITH

      -- For batching by encounters
      batch_encounters as (
          SELECT * FROM encounters
          WHERE id > $fromId
          AND deleted_at IS NULL
          ORDER BY id
          LIMIT $limit
      ),

      ordered_discharges AS
      (
          SELECT discharges.id,
          discharges.encounter_id,
          row_number() over (PARTITION BY encounter_id ORDER BY encounter_id, discharges.created_at ASC) as row_num
          FROM discharges
          JOIN batch_encounters ON batch_encounters.id = discharges.encounter_id
          WHERE discharges.deleted_at IS NULL
      ),

      deleted_discharges AS
      (
          UPDATE discharges
          SET deleted_at = now()
          WHERE id IN (SELECT id FROM ordered_discharges WHERE row_num > 1)
          RETURNING encounter_id
      )

      SELECT MAX(id) as "maxId" FROM batch_encounters;
    `;
    }
    constructor(...args){
        super(...args), _define_property(this, "lastMaxId", '');
    }
};
_define_property(RemoveDuplicatedDischarges, "defaultBatchSize", Number.MAX_SAFE_INTEGER);
_define_property(RemoveDuplicatedDischarges, "defaultDelayMs", 50);

//# sourceMappingURL=RemoveDuplicatedDischarges.js.map