"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "ContributingDeathCause", {
    enumerable: true,
    get: function() {
        return ContributingDeathCause;
    }
});
const _sequelize = require("sequelize");
const _constants = require("@tamanu/constants");
const _errors = require("@tamanu/errors");
const _Model = require("./Model");
const _buildSyncLookupSelect = require("../sync/buildSyncLookupSelect");
let ContributingDeathCause = class ContributingDeathCause extends _Model.Model {
    static initModel({ primaryKey, ...options }) {
        super.init({
            id: primaryKey,
            timeAfterOnset: {
                type: _sequelize.DataTypes.INTEGER,
                allowNull: false
            }
        }, {
            ...options,
            syncDirection: _constants.SYNC_DIRECTIONS.BIDIRECTIONAL,
            validate: {
                mustHavePatientDeathData () {
                    if (this.deletedAt) return;
                    if (!this.patientDeathDataId) {
                        throw new _errors.InvalidOperationError('Cause of death must be attached to a PatientDeathData object.');
                    }
                },
                mustHaveCondition () {
                    if (this.deletedAt) return;
                    if (!this.conditionId) {
                        throw new _errors.InvalidOperationError('Cause of death must have a condition.');
                    }
                }
            }
        });
    }
    static initRelations(models) {
        this.belongsTo(models.PatientDeathData, {
            foreignKey: 'patientDeathDataId',
            as: 'patientDeathData'
        });
        this.belongsTo(models.ReferenceData, {
            foreignKey: 'conditionId',
            as: 'condition'
        });
    }
    static buildPatientSyncFilter(patientCount, markedForSyncPatientsTable) {
        if (patientCount === 0) {
            return null;
        }
        return `
      JOIN
        patient_death_data
      ON
        patient_death_data_id = patient_death_data.id
      WHERE
        patient_death_data.patient_id IN (SELECT patient_id FROM ${markedForSyncPatientsTable})
      AND
        contributing_death_causes.updated_at_sync_tick > :since
    `;
    }
    static async buildSyncLookupQueryDetails() {
        return {
            select: await (0, _buildSyncLookupSelect.buildSyncLookupSelect)(this, {
                patientId: 'patient_death_data.patient_id'
            }),
            joins: `
        JOIN
          patient_death_data
        ON
          patient_death_data_id = patient_death_data.id
      `
        };
    }
};

//# sourceMappingURL=ContributingDeathCause.js.map