"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "Referral", {
    enumerable: true,
    get: function() {
        return Referral;
    }
});
const _sequelize = require("sequelize");
const _constants = require("@tamanu/constants");
const _Model = require("./Model");
const _buildEncounterLinkedLookupFilter = require("../sync/buildEncounterLinkedLookupFilter");
let Referral = class Referral extends _Model.Model {
    static initModel({ primaryKey, ...options }) {
        super.init({
            id: primaryKey,
            referredFacility: _sequelize.DataTypes.STRING,
            status: {
                type: _sequelize.DataTypes.STRING,
                allowNull: false,
                defaultValue: _constants.REFERRAL_STATUSES.PENDING
            }
        }, {
            ...options,
            syncDirection: _constants.SYNC_DIRECTIONS.BIDIRECTIONAL
        });
    }
    static getListReferenceAssociations() {
        return [
            'surveyResponse'
        ];
    }
    static initRelations(models) {
        this.belongsTo(models.Encounter, {
            foreignKey: 'initiatingEncounterId',
            as: 'initiatingEncounter'
        });
        this.belongsTo(models.Encounter, {
            foreignKey: 'completingEncounterId',
            as: 'completingEncounter'
        });
        this.belongsTo(models.SurveyResponse, {
            foreignKey: 'surveyResponseId',
            as: 'surveyResponse'
        });
    }
    static buildPatientSyncFilter(patientCount, markedForSyncPatientsTable) {
        if (patientCount === 0) {
            return null;
        }
        return `
      JOIN encounters ON referrals.initiating_encounter_id = encounters.id
      WHERE encounters.patient_id IN (SELECT patient_id FROM ${markedForSyncPatientsTable})
      AND ${this.tableName}.updated_at_sync_tick > :since
    `;
    }
    static async buildSyncLookupQueryDetails() {
        return {
            select: await (0, _buildEncounterLinkedLookupFilter.buildEncounterLinkedLookupSelect)(this),
            joins: (0, _buildEncounterLinkedLookupFilter.buildEncounterLinkedLookupJoins)(this, [
                {
                    model: this.sequelize.models.Encounter,
                    joinColumn: 'initiating_encounter_id',
                    required: true
                }
            ])
        };
    }
};

//# sourceMappingURL=Referral.js.map