"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.EventsGetHandler = void 0;
const events_get_js_1 = require("../interfaces/events-get.js");
const message_reply_js_1 = require("../core/message-reply.js");
const auth_js_1 = require("../core/auth.js");
class EventsGetHandler {
    constructor(didResolver, eventLog) {
        this.didResolver = didResolver;
        this.eventLog = eventLog;
    }
    handle({ tenant, message }) {
        return __awaiter(this, void 0, void 0, function* () {
            let eventsGet;
            try {
                eventsGet = yield events_get_js_1.EventsGet.parse(message);
            }
            catch (e) {
                return (0, message_reply_js_1.messageReplyFromError)(e, 400);
            }
            try {
                yield (0, auth_js_1.authenticate)(message.authorization, this.didResolver);
                yield (0, auth_js_1.authorize)(tenant, eventsGet);
            }
            catch (e) {
                return (0, message_reply_js_1.messageReplyFromError)(e, 401);
            }
            // if watermark was provided in message, get all events _after_ the watermark.
            // Otherwise, get all events.
            let options;
            if (message.descriptor.watermark) {
                options = { gt: message.descriptor.watermark };
            }
            const events = yield this.eventLog.getEvents(tenant, options);
            return {
                status: { code: 200, detail: 'OK' },
                events
            };
        });
    }
}
exports.EventsGetHandler = EventsGetHandler;
//# sourceMappingURL=events-get.js.map