import config from 'config';
import { DataTypes, Op } from 'sequelize';
import { COMMUNICATION_STATUSES, COMMUNICATION_STATUSES_VALUES, PATIENT_COMMUNICATION_CHANNELS_VALUES, PATIENT_COMMUNICATION_TYPES_VALUES, SYNC_DIRECTIONS } from '@tamanu/constants';
import { Model } from './Model';
export class PatientCommunication extends Model {
    static initModel({ primaryKey, ...options }) {
        super.init({
            id: primaryKey,
            type: {
                type: DataTypes.ENUM(...PATIENT_COMMUNICATION_TYPES_VALUES),
                allowNull: false
            },
            channel: {
                type: DataTypes.ENUM(...PATIENT_COMMUNICATION_CHANNELS_VALUES),
                allowNull: false
            },
            subject: DataTypes.TEXT,
            content: DataTypes.TEXT,
            status: {
                type: DataTypes.ENUM(...COMMUNICATION_STATUSES_VALUES),
                allowNull: false,
                defaultValue: COMMUNICATION_STATUSES.QUEUED
            },
            error: DataTypes.TEXT,
            retryCount: DataTypes.INTEGER,
            destination: DataTypes.STRING,
            attachment: DataTypes.STRING,
            hash: DataTypes.INTEGER
        }, {
            ...options,
            syncDirection: SYNC_DIRECTIONS.PUSH_TO_CENTRAL_THEN_DELETE
        });
    }
    static initRelations(models) {
        this.belongsTo(models.Patient, {
            foreignKey: 'patientId',
            as: 'patient'
        });
    }
    static getBaseQueryPendingMessage(channel) {
        const threshold = config.patientCommunication?.retryThreshold;
        return {
            where: {
                status: COMMUNICATION_STATUSES.QUEUED,
                channel,
                [Op.or]: [
                    {
                        retryCount: {
                            [Op.lte]: threshold
                        }
                    },
                    {
                        retryCount: null
                    }
                ]
            }
        };
    }
    static getPendingMessages(channel, queryOptions) {
        return this.findAll({
            ...this.getBaseQueryPendingMessage(channel),
            order: [
                [
                    this.sequelize.literal('retry_count IS NULL'),
                    'DESC'
                ],
                [
                    'retryCount',
                    'ASC'
                ],
                [
                    'createdAt',
                    'ASC'
                ]
            ],
            ...queryOptions
        });
    }
    static countPendingMessages(channel) {
        return this.count(this.getBaseQueryPendingMessage(channel));
    }
}

//# sourceMappingURL=PatientCommunication.js.map