"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get down () {
        return down;
    },
    get up () {
        return up;
    }
});
const _constants = require("@tamanu/constants");
const _sequelize = require("sequelize");
async function up(query) {
    const nullCountResult = await query.sequelize.query(`SELECT COUNT(*)::text as count FROM encounters WHERE patient_id IS NULL;`, {
        type: _sequelize.QueryTypes.SELECT
    });
    const nullCount = parseInt(nullCountResult[0]?.count ?? '0', 10);
    if (nullCount === 0) {
        return;
    }
    const testPatientResult = await query.sequelize.query(`SELECT id FROM patients WHERE id = :testPatientId AND deleted_at IS NULL LIMIT 1;`, {
        type: _sequelize.QueryTypes.SELECT,
        replacements: {
            testPatientId: _constants.TEST_PATIENT_ID
        }
    });
    const testPatientExists = testPatientResult.length === 1;
    if (!testPatientExists) {
        throw new Error(`Cannot backfill encounters: ${nullCount} encounter(s) have null patient_id,
        but the test patient (id = ${_constants.TEST_PATIENT_ID}) does not exist.
        Ensure the test patient exists before running this migration.`);
    }
    await query.sequelize.query(`UPDATE encounters SET patient_id = :testPatientId WHERE patient_id IS NULL;`, {
        replacements: {
            testPatientId: _constants.TEST_PATIENT_ID
        }
    });
}
async function down(_query) {
// DESTRUCTIVE: Cannot restore original null patient_id values for backfilled rows
}

//# sourceMappingURL=1771277622908-backfillEncountersPatientIdToTestPatient.js.map