"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IccReceiptXApi = void 0;
const icc_api_1 = require("../icc-api");
const models = require("../icc-api/model/models");
const AuthenticationProvider_1 = require("./auth/AuthenticationProvider");
const ShareMetadataBehaviour_1 = require("./crypto/ShareMetadataBehaviour");
const SecureDelegation_1 = require("../icc-api/model/SecureDelegation");
var AccessLevelEnum = SecureDelegation_1.SecureDelegation.AccessLevelEnum;
const utils_1 = require("./utils");
const compression_utils_1 = require("./utils/compression-utils");
class IccReceiptXApi extends icc_api_1.IccReceiptApi {
    get headers() {
        return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, utils_1.EntityWithDelegationTypeName.Receipt));
    }
    constructor(host, headers, crypto, dataOwnerApi, autofillAuthor, authenticationProvider = new AuthenticationProvider_1.NoAuthenticationProvider(), fetchImpl = typeof window !== 'undefined'
        ? window.fetch
        : typeof self !== 'undefined'
            ? self.fetch
            : fetch) {
        super(host, headers, authenticationProvider, fetchImpl);
        this.crypto = crypto;
        this.dataOwnerApi = dataOwnerApi;
        this.autofillAuthor = autofillAuthor;
        this.dataOwnerApi = dataOwnerApi;
    }
    /**
     * Creates a new instance of receipt with initialised encryption metadata (not in the database).
     * @param user the current user.
     * @param r initialised data for the receipt. Metadata such as id, creation data, etc. will be automatically initialised, but you can specify
     * other kinds of data or overwrite generated metadata with this. You can't specify encryption metadata.
     * @param options optional parameters:
     * - additionalDelegates: delegates which will have access to the entity in addition to the current data owner and delegates from the
     * auto-delegations. Must be an object which associates each data owner id with the access level to give to that data owner. May overlap with
     * auto-delegations, in such case the access level specified here will be used.
     * - ignoreAutoDelegations: if true the data won't be shared with the autodelegations of the user, but only with additional delegates
     * - alternateRootDelegation: by default a new entity is created with a root delegation from self to self. In keyless mode this is not possible,
     * and instead the root delegation will be from self to another. You have to specify which delegate will be part of the root delegation.
     * @return a new instance of receipt.
     */
    newInstance(user_1, r_1) {
        return __awaiter(this, arguments, void 0, function* (user, r, options = {}) {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
            const receipt = new models.Receipt(Object.assign(Object.assign({}, (r !== null && r !== void 0 ? r : {})), { _type: 'org.taktik.icure.entities.Receipt', id: (_a = r === null || r === void 0 ? void 0 : r.id) !== null && _a !== void 0 ? _a : this.crypto.primitives.randomUuid(), created: (_b = r === null || r === void 0 ? void 0 : r.created) !== null && _b !== void 0 ? _b : new Date().getTime(), modified: (_c = r === null || r === void 0 ? void 0 : r.modified) !== null && _c !== void 0 ? _c : new Date().getTime(), responsible: (_d = r === null || r === void 0 ? void 0 : r.responsible) !== null && _d !== void 0 ? _d : (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined), author: (_e = r === null || r === void 0 ? void 0 : r.author) !== null && _e !== void 0 ? _e : (this.autofillAuthor ? user.id : undefined), codes: (_f = r === null || r === void 0 ? void 0 : r.codes) !== null && _f !== void 0 ? _f : [], tags: (_g = r === null || r === void 0 ? void 0 : r.tags) !== null && _g !== void 0 ? _g : [] }));
            const extraDelegations = Object.assign(Object.assign({}, (options.ignoreAutoDelegations == true
                ? {}
                : Object.fromEntries([...((_j = (_h = user.autoDelegations) === null || _h === void 0 ? void 0 : _h.all) !== null && _j !== void 0 ? _j : []), ...((_l = (_k = user.autoDelegations) === null || _k === void 0 ? void 0 : _k.medicalInformation) !== null && _l !== void 0 ? _l : [])].map((d) => [d, AccessLevelEnum.WRITE])))), ((_m = options === null || options === void 0 ? void 0 : options.additionalDelegates) !== null && _m !== void 0 ? _m : {}));
            return new models.Receipt(yield this.crypto.xapi
                .entityWithInitialisedEncryptedMetadata(receipt, utils_1.EntityWithDelegationTypeName.Receipt, undefined, undefined, true, extraDelegations, options.alternateRootDelegation)
                .then((x) => x.updatedEntity));
        });
    }
    /**
     * Creates a new receipt linked to a document and optionally attaches a blob to it.
     * @param user the current user.
     * @param docId the id of the document this receipt refers to.
     * @param refs an array of reference strings to associate with the receipt.
     * @param blobType the type of the blob attachment.
     * @param blob the binary content to attach; if empty (byteLength == 0), no attachment is set.
     * @return the created receipt, with the attachment set if the blob was non-empty.
     */
    logReceipt(user, docId, refs, blobType, blob) {
        return this.newInstance(user, { documentId: docId, references: refs })
            .then((rcpt) => this.createReceipt(rcpt))
            .then((rcpt) => (blob.byteLength != 0 ? this.setReceiptAttachmentForBlobType(rcpt.id, rcpt.rev, blobType, blob) : Promise.resolve(rcpt)));
    }
    /**
     * Adds an attachment to a receipt, encrypting it on client side using the encryption keys of the provided receipt.
     * @param receipt a receipt.
     * @param blobType the type of the attachment.
     * @param attachment a attachment for the receipt.
     * @return the updated receipt.
     */
    encryptAndSetReceiptAttachment(receipt, blobType, attachment) {
        return __awaiter(this, void 0, void 0, function* () {
            var _a;
            const { encryptedData, updatedEntity } = yield this.crypto.xapi.encryptDataOf(receipt, utils_1.EntityWithDelegationTypeName.Receipt, attachment, (r) => this.modifyReceipt(r));
            return yield this.setReceiptAttachmentForBlobType(receipt.id, (_a = updatedEntity === null || updatedEntity === void 0 ? void 0 : updatedEntity.rev) !== null && _a !== void 0 ? _a : receipt.rev, blobType, encryptedData);
        });
    }
    /**
     * Adds an unencrypted attachment to a receipt.
     * @param receipt a receipt.
     * @param blobType the type of the attachment.
     * @param attachment a attachment for the receipt.
     * @return the updated receipt.
     */
    setClearReceiptAttachment(receipt, blobType, attachment) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.setReceiptAttachmentForBlobType(receipt.id, receipt.rev, blobType, (0, utils_1.ua2ab)(attachment));
        });
    }
    /**
     * Gets the attachment of a receipt and tries to decrypt it using the encryption keys of the receipt.
     * @param receipt a receipt.
     * @param attachmentId id of the attachment of this receipt to retrieve.
     * @param validator optionally a validator function which checks if the decryption was successful. In cases where the receipt has many encryption
     * keys and it is unclear which one should be used this function can help to detect bad decryptions.
     * @return the decrypted attachment, if it could be decrypted, else the encrypted attachment.
     */
    getAndDecryptReceiptAttachment(receipt_1, attachmentId_1) {
        return __awaiter(this, arguments, void 0, function* (receipt, attachmentId, validator = () => Promise.resolve(true)) {
            const retrieved = yield this.getAndTryDecryptReceiptAttachment(receipt, attachmentId, (x) => validator(x));
            if (!retrieved.wasDecrypted)
                throw new Error(`No valid key found to decrypt data of receipt ${receipt.id}.`);
            return retrieved.data;
        });
    }
    /**
     * Gets the attachment of a receipt and tries to decrypt it using the encryption keys of the receipt.
     * @param receipt a receipt.
     * @param attachmentId id of the attachment of this receipt to retrieve.
     * @param validator optionally a validator function which checks if the decryption was successful. In cases where the receipt has many encryption
     * keys and it is unclear which one should be used this function can help to detect bad decryptions.
     * @return an object containing:
     * - data: the decrypted attachment, if it could be decrypted, else the encrypted attachment.
     * - wasDecrypted: if the data was successfully decrypted or not
     */
    getAndTryDecryptReceiptAttachment(receipt_1, attachmentId_1) {
        return __awaiter(this, arguments, void 0, function* (receipt, attachmentId, validator = () => Promise.resolve(true)) {
            return yield this.crypto.xapi.tryDecryptDataOf({ entity: receipt, type: utils_1.EntityWithDelegationTypeName.Receipt }, yield this.getReceiptAttachment(receipt.id, attachmentId), (x) => __awaiter(this, void 0, void 0, function* () { return ((yield validator(x)) ? x : undefined); }));
        });
    }
    // --- New data attachment methods (with compression support) ---
    /**
     * Compresses, encrypts, and uploads a receipt attachment using the new data attachment endpoint.
     * Compression is attempted automatically; if the compressed result is not smaller, the original data is used.
     * @param receipt a receipt.
     * @param blobType the type of the attachment.
     * @param attachment the raw attachment data.
     * @param deflate if true, compress the attachment before uploading. Reliable decompression of compressed data requires version 26.5 of the API and all users to be using at least version 8.7.0 of the SDK    * @return the updated receipt.
     */
    encryptCompressAndSetReceiptDataAttachment(receipt_1, blobType_1, attachment_1) {
        return __awaiter(this, arguments, void 0, function* (receipt, blobType, attachment, deflate = false) {
            var _a;
            const realDataSize = (0, utils_1.ua2ab)(attachment).byteLength;
            const { data: dataToEncrypt, algorithm: compressionAlgorithm } = deflate
                ? yield (0, compression_utils_1.compressData)(attachment)
                : { data: (0, utils_1.ua2ab)(attachment), algorithm: undefined };
            const { encryptedData, updatedEntity } = yield this.crypto.xapi.encryptDataOf(receipt, utils_1.EntityWithDelegationTypeName.Receipt, dataToEncrypt, (r) => this.modifyReceipt(r));
            return yield this.setReceiptDataAttachment(receipt.id, blobType, (_a = updatedEntity === null || updatedEntity === void 0 ? void 0 : updatedEntity.rev) !== null && _a !== void 0 ? _a : receipt.rev, encryptedData, compressionAlgorithm, (0, compression_utils_1.getCompressionVersion)(), realDataSize);
        });
    }
    /**
     * Compresses and uploads an unencrypted receipt attachment using the new data attachment endpoint.
     * Compression is attempted automatically; if the compressed result is not smaller, the original data is used.
     * @param receipt a receipt.
     * @param blobType the type of the attachment.
     * @param attachment the raw attachment data.
     * @param deflate if true, compress the attachment before uploading. Reliable decompression of compressed data requires version 26.5 of the API and all users to be using at least version 8.7.0 of the SDK    * @return the updated receipt.
     */
    setClearReceiptDataAttachment(receipt_1, blobType_1, attachment_1) {
        return __awaiter(this, arguments, void 0, function* (receipt, blobType, attachment, deflate = false) {
            const realDataSize = (0, utils_1.ua2ab)(attachment).byteLength;
            const { data: dataToUpload, algorithm: compressionAlgorithm } = deflate
                ? yield (0, compression_utils_1.compressData)(attachment)
                : { data: (0, utils_1.ua2ab)(attachment), algorithm: undefined };
            return yield this.setReceiptDataAttachment(receipt.id, blobType, receipt.rev, dataToUpload, compressionAlgorithm, (0, compression_utils_1.getCompressionVersion)(), realDataSize);
        });
    }
    /**
     * Gets a receipt's data attachment by blob type, decrypts it, and decompresses if needed.
     * Throws if decryption fails.
     * @param receipt a receipt.
     * @param blobType the blob type of the attachment to retrieve.
     * @param validator optionally a validator function which checks if the decryption was successful.
     * @return the decrypted (and decompressed) attachment.
     */
    getAndDecryptReceiptDataAttachment(receipt_1, blobType_1) {
        return __awaiter(this, arguments, void 0, function* (receipt, blobType, validator = () => Promise.resolve(true)) {
            const retrieved = yield this.getAndTryDecryptReceiptDataAttachment(receipt, blobType, validator);
            if (!retrieved.wasDecrypted)
                throw new Error(`No valid key found to decrypt data of receipt ${receipt.id}.`);
            return retrieved.data;
        });
    }
    /**
     * Gets a receipt's data attachment by blob type, tries to decrypt it, and decompresses if needed.
     * @param receipt a receipt.
     * @param blobType the blob type of the attachment to retrieve.
     * @param validator optionally a validator function which checks if the decryption was successful.
     * @return an object containing:
     * - data: the decrypted (and decompressed) attachment, or the raw data if decryption failed.
     * - wasDecrypted: if the data was successfully decrypted or not.
     */
    getAndTryDecryptReceiptDataAttachment(receipt_1, blobType_1) {
        return __awaiter(this, arguments, void 0, function* (receipt, blobType, validator = () => Promise.resolve(true)) {
            var _a, _b;
            const compressionAlgorithm = (_b = (_a = receipt.attachmentInfos) === null || _a === void 0 ? void 0 : _a[blobType]) === null || _b === void 0 ? void 0 : _b.compressionAlgorithm;
            return yield this.crypto.xapi.tryDecryptDataOf({ entity: receipt, type: utils_1.EntityWithDelegationTypeName.Receipt }, yield this.getReceiptAttachmentByBlobType(receipt.id, blobType), (decrypted) => __awaiter(this, void 0, void 0, function* () {
                try {
                    const data = compressionAlgorithm ? yield (0, compression_utils_1.decompressData)(decrypted, compressionAlgorithm) : decrypted;
                    return (yield validator(data)) ? data : undefined;
                }
                catch (_a) {
                    return undefined;
                }
            }));
        });
    }
    /**
     * @return if the logged data owner has write access to the content of the given receipt
     */
    hasWriteAccess(receipt) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.crypto.xapi.hasWriteAccess({ entity: receipt, type: utils_1.EntityWithDelegationTypeName.Receipt });
        });
    }
    /**
     * Share an existing receipt with other data owners, allowing them to access the non-encrypted data of the receipt and optionally also
     * the encrypted content, with read-only or read-write permissions.
     * @param delegateId the id of the data owner which will be granted access to the receipt.
     * @param receipt the receipt to share.
     * @param options optional parameters to customize the sharing behaviour:
     * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared
     * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted
     * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a
     * receipt does not have encrypted content.
     * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.
     * @return the updated entity
     */
    shareWith(delegateId_1, receipt_1) {
        return __awaiter(this, arguments, void 0, function* (delegateId, receipt, options = {}) {
            return this.shareWithMany(receipt, { [delegateId]: options });
        });
    }
    /**
     * Share an existing receipt with other data owners, allowing them to access the non-encrypted data of the receipt and optionally also
     * the encrypted content, with read-only or read-write permissions.
     * @param receipt the receipt to share.
     * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:
     * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared
     * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted
     * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a
     * receipt does not have encrypted content.
     * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.
     * @return the updated entity
     */
    shareWithMany(receipt, delegates) {
        return __awaiter(this, void 0, void 0, function* () {
            return (yield this.tryShareWithMany(receipt, delegates)).updatedEntityOrThrow;
        });
    }
    /**
     * Share an existing receipt with other data owners, allowing them to access the non-encrypted data of the receipt and optionally also
     * the encrypted content, with read-only or read-write permissions.
     * @param receipt the receipt to share.
     * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:
     * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared
     * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted
     * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a
     * receipt does not have encrypted content.
     * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.
     * @return a promise which will contain the result of the operation: the updated entity if the operation was successful or details of the error if
     * the operation failed.
     */
    tryShareWithMany(receipt, delegates) {
        return __awaiter(this, void 0, void 0, function* () {
            // All entities should have an encryption key.
            const entityWithEncryptionKey = yield this.crypto.xapi.ensureEncryptionKeysInitialised(receipt, utils_1.EntityWithDelegationTypeName.Receipt);
            const updatedEntity = entityWithEncryptionKey ? yield this.modifyReceipt(entityWithEncryptionKey) : receipt;
            return this.crypto.xapi.simpleShareOrUpdateEncryptedEntityMetadata({
                entity: updatedEntity,
                type: utils_1.EntityWithDelegationTypeName.Receipt,
            }, Object.fromEntries(Object.entries(delegates).map(([delegateId, options]) => [
                delegateId,
                {
                    requestedPermissions: options.requestedPermissions,
                    shareEncryptionKeys: options.shareEncryptionKey,
                    shareOwningEntityIds: ShareMetadataBehaviour_1.ShareMetadataBehaviour.NEVER,
                    shareSecretIds: options.shareSecretIds,
                },
            ])), (x) => this.bulkShareReceipt(x));
        });
    }
    /**
     * Retrieves the data owners that have access to the given receipt, along with their access levels.
     * @param entity the receipt.
     * @return an object containing a map of data owner ids to their access levels, and a flag indicating if there are unknown anonymous data owners.
     */
    getDataOwnersWithAccessTo(entity) {
        return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: utils_1.EntityWithDelegationTypeName.Receipt });
    }
    /**
     * Retrieves the encryption keys of the given receipt.
     * @param entity the receipt.
     * @return the encryption key ids.
     */
    getEncryptionKeysOf(entity) {
        return this.crypto.xapi.encryptionKeysOf({ entity, type: utils_1.EntityWithDelegationTypeName.Receipt }, undefined);
    }
    /**
     * Creates or updates de-anonymization metadata for the given receipt, allowing the specified delegates to
     * identify the data owners that have access to it.
     * @param entity the receipt.
     * @param delegates the data owner ids for which to create de-anonymization metadata.
     */
    createDelegationDeAnonymizationMetadata(entity, delegates) {
        return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: utils_1.EntityWithDelegationTypeName.Receipt }, delegates);
    }
}
exports.IccReceiptXApi = IccReceiptXApi;
//# sourceMappingURL=icc-receipt-x-api.js.map