"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "PatientFacility", {
    enumerable: true,
    get: function() {
        return PatientFacility;
    }
});
const _sequelize = require("sequelize");
const _constants = require("@tamanu/constants");
const _Model = require("./Model");
const _buildSyncLookupSelect = require("../sync/buildSyncLookupSelect");
let PatientFacility = class PatientFacility extends _Model.Model {
    static initModel(options) {
        super.init({
            id: {
                // patient facility records use a generated primary key that enforces one per patient,
                // even across a distributed sync system
                type: `TEXT GENERATED ALWAYS AS (REPLACE("patient_id", ';', ':') || ';' || REPLACE("facility_id", ';', ':')) STORED`,
                set () {
                // any sets of the convenience generated "id" field can be ignored
                }
            },
            patientId: {
                type: _sequelize.DataTypes.STRING,
                primaryKey: true,
                references: {
                    model: 'patients',
                    key: 'id'
                }
            },
            facilityId: {
                type: _sequelize.DataTypes.STRING,
                primaryKey: true,
                references: {
                    model: 'facilities',
                    key: 'id'
                }
            }
        }, {
            ...options,
            syncDirection: _constants.SYNC_DIRECTIONS.BIDIRECTIONAL
        });
    }
    static initRelations(models) {
        this.belongsTo(models.Facility, {
            foreignKey: 'facilityId',
            as: 'facility'
        });
        this.belongsTo(models.Patient, {
            foreignKey: 'patientId',
            as: 'patient'
        });
    }
    static buildSyncFilter() {
        return `WHERE facility_id in (:facilityIds) AND ${this.tableName}.updated_at_sync_tick > :since`;
    }
    static async buildSyncLookupQueryDetails() {
        return {
            select: await (0, _buildSyncLookupSelect.buildSyncLookupSelect)(this, {
                facilityId: `${this.tableName}.facility_id`
            })
        };
    }
};

//# sourceMappingURL=PatientFacility.js.map