// retoor <retoor@molodetz.nl>

const STORAGE_KEY = "devrant-docs-auth";

class DevRantSession {
    constructor() {
        const docs = window.DEVPLACE_DOCS || {};
        this.base = docs.base || location.origin;
        this.auth = null;
        this.username = "";
        this.listeners = new Set();
        try {
            const raw = localStorage.getItem(STORAGE_KEY);
            if (raw) {
                const parsed = JSON.parse(raw);
                this.auth = parsed.auth || null;
                this.username = parsed.username || "";
            }
        } catch {
            this.auth = null;
        }
    }

    isLoggedIn() {
        return Boolean(this.auth && this.auth.token_key);
    }

    triple() {
        return this.isLoggedIn() ? { ...this.auth } : {};
    }

    onChange(callback) {
        this.listeners.add(callback);
        return () => this.listeners.delete(callback);
    }

    _emit() {
        for (const callback of this.listeners) callback();
    }

    _persist() {
        try {
            localStorage.setItem(
                STORAGE_KEY,
                JSON.stringify({ auth: this.auth, username: this.username }),
            );
        } catch {
            return;
        }
    }

    setFromToken(token, username) {
        this.auth = {
            user_id: token.user_id,
            token_id: token.id,
            token_key: token.key,
        };
        if (username) this.username = username;
        this._persist();
        this._emit();
    }

    async login(username, password) {
        const response = await fetch(`${this.base}/api/users/auth-token`, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                Accept: "application/json",
            },
            body: new URLSearchParams({ username, password }).toString(),
        });
        const data = await response.json();
        if (!data.success) throw new Error(data.error || "login failed");
        this.setFromToken(data.auth_token, username);
        return this.auth;
    }

    logout() {
        this.auth = null;
        this.username = "";
        this._persist();
        this._emit();
    }
}

export const devrantSession = new DevRantSession();
