"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.constructRecordsWriteIndexes = exports.RecordsWriteHandler = void 0;
var auth_js_1 = require("../../../core/auth.js");
var records_interface_js_1 = require("../records-interface.js");
var message_reply_js_1 = require("../../../core/message-reply.js");
var records_write_js_1 = require("../messages/records-write.js");
var dwn_error_js_1 = require("../../../core/dwn-error.js");
var message_js_1 = require("../../../core/message.js");
var RecordsWriteHandler = /** @class */ (function () {
    function RecordsWriteHandler(didResolver, messageStore, dataStore, eventLog) {
        this.didResolver = didResolver;
        this.messageStore = messageStore;
        this.dataStore = dataStore;
        this.eventLog = eventLog;
    }
    RecordsWriteHandler.prototype.handle = function (_a) {
        var tenant = _a.tenant, message = _a.message, options = _a.options, dataStream = _a.dataStream;
        return __awaiter(this, void 0, void 0, function () {
            var recordsWrite, e_1, e_2, query, existingMessages, newMessageIsInitialWrite, initialWrite, e_3, newestExistingMessage, incomingMessageIsNewest, newestMessage, _b, isLatestBaseState, indexes, error_1, e, _c, _d, _e, messageReply;
            return __generator(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        _f.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, records_write_js_1.RecordsWrite.parse(message)];
                    case 1:
                        recordsWrite = _f.sent();
                        return [3 /*break*/, 3];
                    case 2:
                        e_1 = _f.sent();
                        return [2 /*return*/, message_reply_js_1.MessageReply.fromError(e_1, 400)];
                    case 3:
                        _f.trys.push([3, 6, , 7]);
                        return [4 /*yield*/, (0, auth_js_1.authenticate)(message.authorization, this.didResolver)];
                    case 4:
                        _f.sent();
                        return [4 /*yield*/, recordsWrite.authorize(tenant, this.messageStore)];
                    case 5:
                        _f.sent();
                        return [3 /*break*/, 7];
                    case 6:
                        e_2 = _f.sent();
                        return [2 /*return*/, message_reply_js_1.MessageReply.fromError(e_2, 401)];
                    case 7:
                        query = {
                            interface: message_js_1.DwnInterfaceName.Records,
                            recordId: message.recordId
                        };
                        return [4 /*yield*/, this.messageStore.query(tenant, query)];
                    case 8:
                        existingMessages = _f.sent();
                        return [4 /*yield*/, recordsWrite.isInitialWrite()];
                    case 9:
                        newMessageIsInitialWrite = _f.sent();
                        if (!!newMessageIsInitialWrite) return [3 /*break*/, 13];
                        _f.label = 10;
                    case 10:
                        _f.trys.push([10, 12, , 13]);
                        return [4 /*yield*/, records_write_js_1.RecordsWrite.getInitialWrite(existingMessages)];
                    case 11:
                        initialWrite = _f.sent();
                        records_write_js_1.RecordsWrite.verifyEqualityOfImmutableProperties(initialWrite, message);
                        return [3 /*break*/, 13];
                    case 12:
                        e_3 = _f.sent();
                        return [2 /*return*/, message_reply_js_1.MessageReply.fromError(e_3, 400)];
                    case 13: return [4 /*yield*/, message_js_1.Message.getNewestMessage(existingMessages)];
                    case 14:
                        newestExistingMessage = _f.sent();
                        incomingMessageIsNewest = false;
                        _b = newestExistingMessage === undefined;
                        if (_b) return [3 /*break*/, 16];
                        return [4 /*yield*/, message_js_1.Message.isNewer(message, newestExistingMessage)];
                    case 15:
                        _b = (_f.sent());
                        _f.label = 16;
                    case 16:
                        if (_b) {
                            incomingMessageIsNewest = true;
                            newestMessage = message;
                        }
                        else { // existing message is the same age or newer than the incoming message
                            newestMessage = newestExistingMessage;
                        }
                        if (!incomingMessageIsNewest) {
                            return [2 /*return*/, new message_reply_js_1.MessageReply({
                                    status: { code: 409, detail: 'Conflict' }
                                })];
                        }
                        isLatestBaseState = true;
                        return [4 /*yield*/, constructRecordsWriteIndexes(recordsWrite, isLatestBaseState)];
                    case 17:
                        indexes = _f.sent();
                        _f.label = 18;
                    case 18:
                        _f.trys.push([18, 21, , 22]);
                        if (!(options === undefined || !options.skipDataStorage)) return [3 /*break*/, 20];
                        return [4 /*yield*/, this.putData(tenant, message, dataStream, newestExistingMessage)];
                    case 19:
                        _f.sent();
                        _f.label = 20;
                    case 20: return [3 /*break*/, 22];
                    case 21:
                        error_1 = _f.sent();
                        e = error_1;
                        if (e.code === dwn_error_js_1.DwnErrorCode.RecordsWriteMissingDataStream ||
                            e.code === dwn_error_js_1.DwnErrorCode.RecordsWriteMissingData ||
                            e.code === dwn_error_js_1.DwnErrorCode.RecordsWriteDataCidMismatch ||
                            e.code === dwn_error_js_1.DwnErrorCode.RecordsWriteDataSizeMismatch) {
                            return [2 /*return*/, message_reply_js_1.MessageReply.fromError(error_1, 400)];
                        }
                        // else throw
                        throw error_1;
                    case 22: return [4 /*yield*/, this.messageStore.put(tenant, message, indexes)];
                    case 23:
                        _f.sent();
                        _d = (_c = this.eventLog).append;
                        _e = [tenant];
                        return [4 /*yield*/, message_js_1.Message.getCid(message)];
                    case 24: return [4 /*yield*/, _d.apply(_c, _e.concat([_f.sent()]))];
                    case 25:
                        _f.sent();
                        messageReply = new message_reply_js_1.MessageReply({
                            status: { code: 202, detail: 'Accepted' }
                        });
                        // delete all existing messages that are not newest, except for the initial write
                        return [4 /*yield*/, (0, records_interface_js_1.deleteAllOlderMessagesButKeepInitialWrite)(tenant, existingMessages, newestMessage, this.messageStore, this.dataStore, this.eventLog)];
                    case 26:
                        // delete all existing messages that are not newest, except for the initial write
                        _f.sent();
                        return [2 /*return*/, messageReply];
                }
            });
        });
    };
    ;
    /**
     * Puts the given data in storage unless tenant already has that data for the given recordId
     *
     * @throws {DwnError} with `DwnErrorCode.RecordsWriteMissingDataStream`
     *                    if `dataStream` is absent AND the `dataCid` does not match the current data for the given recordId
     * @throws {DwnError} with `DwnErrorCode.RecordsWriteMissingData`
     *                    if `dataStream` is absent AND dataStore does not contain the given `dataCid`
     * @throws {DwnError} with `DwnErrorCode.RecordsWriteDataCidMismatch`
     *                    if the data stream resulted in a data CID that mismatches with `dataCid` in the given message
     * @throws {DwnError} with `DwnErrorCode.RecordsWriteDataSizeMismatch`
     *                    if `dataSize` in `descriptor` given mismatches the actual data size
     */
    RecordsWriteHandler.prototype.putData = function (tenant, message, dataStream, newestExistingMessage) {
        return __awaiter(this, void 0, void 0, function () {
            var result, messageCid, associateResult;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, message_js_1.Message.getCid(message)];
                    case 1:
                        messageCid = _a.sent();
                        if (!(dataStream === undefined)) return [3 /*break*/, 3];
                        // dataStream must be included if message contains a new dataCid
                        if ((newestExistingMessage === null || newestExistingMessage === void 0 ? void 0 : newestExistingMessage.descriptor.dataCid) !== message.descriptor.dataCid) {
                            throw new dwn_error_js_1.DwnError(dwn_error_js_1.DwnErrorCode.RecordsWriteMissingDataStream, 'Data stream is not provided.');
                        }
                        return [4 /*yield*/, this.dataStore.associate(tenant, messageCid, message.descriptor.dataCid)];
                    case 2:
                        associateResult = _a.sent();
                        if (associateResult === undefined) {
                            throw new dwn_error_js_1.DwnError(dwn_error_js_1.DwnErrorCode.RecordsWriteMissingData, "Unable to associate dataCid ".concat(message.descriptor.dataCid, " ") +
                                "to messageCid ".concat(messageCid, " because dataStream was not provided and data was not found in dataStore"));
                        }
                        result = associateResult;
                        return [3 /*break*/, 5];
                    case 3: return [4 /*yield*/, this.dataStore.put(tenant, messageCid, message.descriptor.dataCid, dataStream)];
                    case 4:
                        result = _a.sent();
                        _a.label = 5;
                    case 5:
                        if (!(message.descriptor.dataSize !== result.dataSize)) return [3 /*break*/, 7];
                        // there is an opportunity to improve here: handle the edge case of if the delete fails...
                        return [4 /*yield*/, this.dataStore.delete(tenant, messageCid, message.descriptor.dataCid)];
                    case 6:
                        // there is an opportunity to improve here: handle the edge case of if the delete fails...
                        _a.sent();
                        throw new dwn_error_js_1.DwnError(dwn_error_js_1.DwnErrorCode.RecordsWriteDataSizeMismatch, "actual data size ".concat(result.dataSize, " bytes does not match dataSize in descriptor: ").concat(message.descriptor.dataSize));
                    case 7:
                        if (!(message.descriptor.dataCid !== result.dataCid)) return [3 /*break*/, 9];
                        // there is an opportunity to improve here: handle the edge cae of if the delete fails...
                        return [4 /*yield*/, this.dataStore.delete(tenant, messageCid, message.descriptor.dataCid)];
                    case 8:
                        // there is an opportunity to improve here: handle the edge cae of if the delete fails...
                        _a.sent();
                        throw new dwn_error_js_1.DwnError(dwn_error_js_1.DwnErrorCode.RecordsWriteDataCidMismatch, "actual data CID ".concat(result.dataCid, " does not match dataCid in descriptor: ").concat(message.descriptor.dataCid));
                    case 9: return [2 /*return*/];
                }
            });
        });
    };
    return RecordsWriteHandler;
}());
exports.RecordsWriteHandler = RecordsWriteHandler;
function constructRecordsWriteIndexes(recordsWrite, isLatestBaseState) {
    return __awaiter(this, void 0, void 0, function () {
        var message, descriptor, indexes, _a;
        var _b;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    message = recordsWrite.message;
                    descriptor = __assign({}, message.descriptor);
                    delete descriptor.published; // handle `published` specifically further down
                    _a = [__assign({}, descriptor)];
                    _b = { isLatestBaseState: isLatestBaseState, published: !!message.descriptor.published, author: recordsWrite.author, recordId: message.recordId };
                    return [4 /*yield*/, records_write_js_1.RecordsWrite.getEntryId(recordsWrite.author, recordsWrite.message.descriptor)];
                case 1:
                    indexes = __assign.apply(void 0, _a.concat([(_b.entryId = _c.sent(), _b)]));
                    if (recordsWrite.attesters.length > 0) {
                        indexes.attester = recordsWrite.attesters[0];
                    }
                    if (message.contextId !== undefined) {
                        indexes.contextId = message.contextId;
                    }
                    return [2 /*return*/, indexes];
            }
        });
    });
}
exports.constructRecordsWriteIndexes = constructRecordsWriteIndexes;
//# sourceMappingURL=records-write.js.map