import { authenticate } from '../core/auth.js';
import { Message } from '../core/message.js';
import { messageReplyFromError } from '../core/message-reply.js';
import { Messages } from '../utils/messages.js';
import { MessagesGrantAuthorization } from '../core/messages-grant-authorization.js';
import { MessagesSubscribe } from '../interfaces/messages-subscribe.js';
import { Time } from '../utils/time.js';
import { DwnError, DwnErrorCode } from '../core/dwn-error.js';
export class MessagesSubscribeHandler {
    deps;
    constructor(deps) {
        this.deps = deps;
    }
    async handle({ tenant, message, subscriptionHandler }) {
        if (this.deps.eventLog === undefined) {
            return messageReplyFromError(new DwnError(DwnErrorCode.MessagesSubscribeEventLogUnimplemented, 'Subscriptions are not supported'), 501);
        }
        let messagesSubscribe;
        try {
            messagesSubscribe = await MessagesSubscribe.parse(message);
        }
        catch (e) {
            return messageReplyFromError(e, 400);
        }
        let authorization;
        try {
            await authenticate(message.authorization, this.deps.didResolver);
            authorization = await MessagesSubscribeHandler.authorizeMessagesSubscribe(tenant, messagesSubscribe, this.deps);
        }
        catch (error) {
            return messageReplyFromError(error, 401);
        }
        const guardedHandler = MessagesSubscribeHandler.createAuthorizationGuard({
            authorization,
            deps: this.deps,
            messagesSubscribe,
            subscriptionHandler,
        });
        const { filters, cursor: eventLogCursor } = message.descriptor;
        const messagesFilters = Messages.convertFilters(filters, this.deps.coreProtocols);
        const messageCid = await Message.getCid(message);
        try {
            const subscription = await this.deps.eventLog.subscribe(tenant, messageCid, guardedHandler.listener, {
                cursor: eventLogCursor,
                filters: messagesFilters,
            });
            await guardedHandler.setSubscription(subscription);
            return {
                status: { code: 200, detail: 'OK' },
                subscription,
            };
        }
        catch (error) {
            if (error instanceof DwnError && error.code === DwnErrorCode.EventLogProgressGap) {
                const gapInfo = error.gapInfo;
                return {
                    status: { code: 410, detail: 'Progress token gap' },
                    error: gapInfo === undefined ? undefined : { code: 'ProgressGap', ...gapInfo },
                };
            }
            return messageReplyFromError(error, 500);
        }
    }
    static async authorizeMessagesSubscribe(tenant, messagesSubscribe, deps) {
        const grantSet = await MessagesGrantAuthorization.authorizeQueryOrSubscribeInvocation({
            tenant: tenant,
            incomingMessage: messagesSubscribe.message,
            validationStateReader: deps.validationStateReader,
            failureCode: DwnErrorCode.MessagesSubscribeAuthorizationFailed,
        });
        if (grantSet === undefined) {
            return { kind: 'owner' };
        }
        return {
            kind: 'delegate',
            expectedGrantor: tenant,
            expectedGrantee: grantSet.requester,
            permissionGrants: grantSet.permissionGrants,
        };
    }
    static createAuthorizationGuard(input) {
        const { authorization, deps, messagesSubscribe, subscriptionHandler } = input;
        if (authorization.kind === 'owner') {
            return {
                listener: subscriptionHandler,
                setSubscription: async () => { },
            };
        }
        let subscription;
        let closeRequested = false;
        let terminalErrorEmitted = false;
        let deliveryQueue = Promise.resolve();
        const closeSubscription = () => {
            if (closeRequested) {
                return;
            }
            closeRequested = true;
            Promise.resolve(subscription?.close()).catch(() => { });
        };
        const emitTerminalDeliveryError = (cursor, code, detail) => {
            if (terminalErrorEmitted) {
                return;
            }
            terminalErrorEmitted = true;
            subscriptionHandler({
                type: 'error',
                cursor,
                error: {
                    code,
                    detail,
                },
            });
        };
        // Deliberately do not cache delivery authorization here. Subscribe-open
        // authorization validates static grant shape and filter scope; this per-event
        // check revalidates dynamic grant state so expiry or revocation stops delivery
        // before the next event is forwarded. Future throughput optimizations should
        // split static and dynamic checks explicitly and document any bounded staleness
        // introduced by caching revocation lookups.
        const authorizeAndDeliverEvent = async (subMessage) => {
            try {
                await MessagesGrantAuthorization.authorizeSubscribeDelivery({
                    messagesSubscribeMessage: messagesSubscribe.message,
                    expectedGrantor: authorization.expectedGrantor,
                    expectedGrantee: authorization.expectedGrantee,
                    permissionGrants: authorization.permissionGrants,
                    validationStateReader: deps.validationStateReader,
                    deliveryTimestamp: Time.getCurrentTimestamp(),
                });
            }
            catch (error) {
                if (error instanceof DwnError) {
                    emitTerminalDeliveryError(subMessage.cursor, DwnErrorCode.MessagesSubscribeDeliveryAuthorizationFailed, 'subscription authorization failed during delivery');
                }
                else {
                    emitTerminalDeliveryError(subMessage.cursor, DwnErrorCode.MessagesSubscribeDeliveryFailed, 'subscription delivery failed');
                }
                closeSubscription();
                return;
            }
            if (!closeRequested) {
                subscriptionHandler(subMessage);
            }
        };
        const deliverQueuedMessage = async (subMessage) => {
            if (closeRequested) {
                return;
            }
            if (subMessage.type !== 'event') {
                subscriptionHandler(subMessage);
                return;
            }
            await authorizeAndDeliverEvent(subMessage);
        };
        const enqueueDelivery = (subMessage) => {
            deliveryQueue = deliveryQueue
                .then(() => deliverQueuedMessage(subMessage))
                .catch(() => { });
        };
        const listener = (subMessage) => {
            enqueueDelivery(subMessage);
        };
        return {
            listener,
            setSubscription: async (eventSubscription) => {
                subscription = eventSubscription;
                if (closeRequested) {
                    await eventSubscription.close();
                }
            },
        };
    }
}
//# sourceMappingURL=messages-subscribe.js.map