// retoor <retoor@molodetz.nl>

import { Http } from "./Http.js";

class AdminNotificationDefaults {
    constructor() {
        this.root = document.querySelector("[data-admin-notif]");
        if (!this.root) return;
        this.root
            .querySelectorAll("[data-notif-toggle]")
            .forEach((input) => this.bind(input));
    }

    bind(input) {
        input.addEventListener("change", async () => {
            const desired = input.checked;
            input.disabled = true;
            try {
                await Http.send("/admin/notifications", {
                    notification_type: input.dataset.type,
                    channel: input.dataset.channel,
                    value: desired ? "true" : "false",
                });
                this.flash(desired ? "Default enabled" : "Default disabled", "success");
            } catch (error) {
                input.checked = !desired;
                this.flash("Could not save default", "error");
            } finally {
                input.disabled = false;
            }
        });
    }

    flash(message, type) {
        if (window.app && window.app.toast) {
            window.app.toast.show(message, { type });
        }
    }
}

window.AdminNotificationDefaults = AdminNotificationDefaults;
export { AdminNotificationDefaults };
