"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "FhirWriteLog", {
    enumerable: true,
    get: function() {
        return FhirWriteLog;
    }
});
const _sequelize = require("sequelize");
const _jsonpath = /*#__PURE__*/ _interop_require_default(require("jsonpath"));
const _constants = require("@tamanu/constants");
const _Model = require("../Model");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
let FhirWriteLog = class FhirWriteLog extends _Model.Model {
    static initModel(options) {
        super.init({
            id: {
                type: _sequelize.DataTypes.UUID,
                allowNull: false,
                defaultValue: _sequelize.Sequelize.fn('gen_random_uuid'),
                primaryKey: true
            },
            createdAt: {
                type: _sequelize.DataTypes.DATE,
                allowNull: false,
                defaultValue: _sequelize.DataTypes.NOW
            },
            verb: {
                type: _sequelize.DataTypes.TEXT,
                allowNull: false
            },
            url: {
                type: _sequelize.DataTypes.TEXT,
                allowNull: false
            },
            body: {
                type: _sequelize.DataTypes.JSONB,
                allowNull: false,
                defaultValue: {}
            },
            headers: {
                type: _sequelize.DataTypes.JSONB,
                allowNull: false,
                defaultValue: {}
            }
        }, {
            ...options,
            syncDirection: _constants.SYNC_DIRECTIONS.DO_NOT_SYNC,
            schema: 'logs',
            tableName: 'fhir_writes',
            timestamps: false
        });
    }
    static initRelations(models) {
        this.belongsTo(models.User, {
            as: 'user',
            foreignKey: 'userId'
        });
    }
    static fromRequest(req) {
        const scrubbedBody = scrubber(JSON.stringify(req.body));
        return this.create({
            verb: req.method,
            url: req.originalUrl,
            body: scrubbedBody,
            headers: filterHeaders(req.headers),
            userId: req.user?.id
        });
    }
};
function filterHeaders(headers) {
    return Object.fromEntries(Object.entries(headers).filter(([key])=>key.startsWith('if-') || key.startsWith('x-') || [
            'accept',
            'client-timezone',
            'content-type',
            'prefer',
            'user-agent'
        ].includes(key)));
}
function scrubber(body) {
    const newBody = JSON.parse(body); // we don't want to change the original request
    return Object.values(_constants.HTTP_BODY_DATA_PATHS).reduce((currentBody, path)=>{
        _jsonpath.default.apply(currentBody, path, ()=>_constants.SCRUBBED_DATA_MESSAGE);
        return currentBody;
    }, newBody);
}

//# sourceMappingURL=WriteLog.js.map