"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "FhirJobWorker", {
    enumerable: true,
    get: function() {
        return FhirJobWorker;
    }
});
const _sequelize = /*#__PURE__*/ _interop_require_wildcard(require("sequelize"));
const _constants = require("@tamanu/constants");
const _Model = require("../Model");
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
let FhirJobWorker = class FhirJobWorker extends _Model.Model {
    static initModel({ primaryKey, ...options }) {
        super.init({
            id: {
                ...primaryKey,
                type: _sequelize.DataTypes.UUID,
                defaultValue: _sequelize.default.fn('gen_random_uuid')
            },
            metadata: {
                type: _sequelize.DataTypes.JSONB,
                allowNull: false,
                defaultValue: {}
            }
        }, {
            ...options,
            schema: 'fhir',
            tableName: 'job_workers',
            syncDirection: _constants.SYNC_DIRECTIONS.DO_NOT_SYNC
        });
    }
    static async register(metadata = {}) {
        const result = await this.sequelize.query('SELECT fhir.job_worker_register($metadata) as id', {
            type: _sequelize.QueryTypes.SELECT,
            bind: {
                metadata
            }
        });
        return FhirJobWorker.findByPk(result?.[0]?.id);
    }
    static async clearDead() {
        await this.sequelize.query('SELECT fhir.job_worker_garbage_collect()');
    }
    async heartbeat() {
        await this.sequelize.query('SELECT fhir.job_worker_heartbeat($workerId)', {
            type: _sequelize.QueryTypes.SELECT,
            bind: {
                workerId: this.id
            }
        });
    }
    async deregister() {
        await this.sequelize.query('SELECT fhir.job_worker_deregister($workerId)', {
            type: _sequelize.QueryTypes.SELECT,
            bind: {
                workerId: this.id
            }
        });
    }
    async markAsHandling(topic) {
        const topics = this.metadata.topics || [];
        await this.update({
            metadata: {
                ...this.metadata,
                topics: [
                    ...topics,
                    topic
                ]
            }
        });
    }
    async recordSuccess() {
        await this.update({
            metadata: {
                ...this.metadata,
                lastSuccessfulJobTimestamp: new Date(),
                successfulJobs: (this.metadata.successfulJobs || 0) + 1,
                totalJobs: (this.metadata.totalJobs || 0) + 1
            }
        });
    }
    async recordFailure() {
        await this.update({
            metadata: {
                ...this.metadata,
                failedJobs: (this.metadata.failedJobs || 0) + 1,
                totalJobs: (this.metadata.totalJobs || 0) + 1
            }
        });
    }
};

//# sourceMappingURL=JobWorker.js.map