"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "uploadAttachment", {
    enumerable: true,
    get: function() {
        return uploadAttachment;
    }
});
const _fs = /*#__PURE__*/ _interop_require_wildcard(require("fs"));
const _errors = require("@tamanu/errors");
const _getUploadedData = require("@tamanu/shared/utils/getUploadedData");
const _sync = require("../sync");
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;
}
const uploadAttachment = async (req, maxFileSize)=>{
    // TODO: Figure out permission management for writing
    // an Attachment
    // req.checkPermission('write', 'Attachment'); ??
    // Read request and extract file, stats and metadata
    const { deviceId } = req;
    const { file, deleteFileAfterImport, type, ...metadata } = await (0, _getUploadedData.getUploadedData)(req);
    const { size } = _fs.default.statSync(file);
    const fileData = await _fs.promises.readFile(file, {
        encoding: 'base64'
    });
    // Parsed file needs to be deleted from memory
    if (deleteFileAfterImport) _fs.default.unlink(file, ()=>null);
    // Check file size constraint
    if (maxFileSize && size > maxFileSize) {
        throw new _errors.InvalidParameterError(`Uploaded file exceeds limit of ${maxFileSize} bytes.`);
    }
    // Upload file to central server
    // CentralServerConnection takes care of adding headers and convert body to JSON
    const centralServer = new _sync.CentralServerConnection({
        deviceId
    });
    const syncResponse = await centralServer.fetch('attachment', {
        method: 'POST',
        body: {
            type,
            size,
            data: fileData
        },
        backoff: {
            maxAttempts: 1
        }
    });
    if (syncResponse.error) {
        throw new _errors.RemoteCallError(syncResponse.error.message);
    }
    // Send parsed metadata along with the new created attachment id
    return {
        attachmentId: syncResponse.attachmentId,
        type,
        metadata
    };
};

//# sourceMappingURL=uploadAttachment.js.map