// retoor <retoor@molodetz.nl>

const TOAST_MS = 6000;

export class LiveNotifications {
    constructor(pubsub, toast) {
        this.pubsub = pubsub;
        this.toast = toast;
        this.uid = document.body.dataset.userUid || "";
        if (!this.uid) return;
        this.topic = `user.${this.uid}.notifications`;
        this.pubsub.subscribe(this.topic, (data) => this.onNotification(data));
    }

    onNotification(data) {
        if (!data || !data.message) return;
        this.toast.show(data.message, {
            type: "info",
            ms: TOAST_MS,
            url: this._openUrl(data),
        });
    }

    _openUrl(data) {
        if (data.uid) return `/notifications/open/${data.uid}`;
        return data.target_url || "/notifications";
    }
}
