/**
 * Reactive state for managing the authenticated account's auth sessions on a
 * settings page. Reads and mutations flow through a narrow RPC adapter backed
 * by `auth/account_actions.ts`.
 *
 * Holds two `AsyncSlot`s — `list` for the fetch, `revoke_all` for the bulk
 * revoke — plus one `KeyedAsyncSlot<string, void>` (`revoke`) keyed by
 * `session_id` for per-row revoke (independent supersession across
 * concurrent rows; per-row error surfacing). Method names use the
 * `submit_*` prefix to avoid slot-name collisions.
 *
 * @module
 */
import { create_context } from '@fuzdev/fuz_ui/context_helpers.js';
import { AsyncSlot } from './async_slot.svelte.js';
import { KeyedAsyncSlot } from './keyed_async_slot.svelte.js';
/**
 * Svelte context carrying the reactive `AccountSessionsRpc` accessor. Mirrors
 * the admin-side RPC contexts. `get()` throws when no provisioner ran above
 * the component — the adapter is required.
 */
export const account_sessions_rpc_context = create_context();
export class AccountSessionsState {
    #get_rpc;
    list = new AsyncSlot();
    revoke = new KeyedAsyncSlot();
    revoke_all = new AsyncSlot();
    sessions = $state.raw([]);
    active_count = $derived(this.sessions.length);
    constructor(options) {
        this.#get_rpc = options.get_rpc;
    }
    async fetch() {
        await this.list.run(async () => {
            const { sessions } = await this.#get_rpc().list();
            this.sessions = sessions;
        });
    }
    async submit_revoke(id) {
        await this.revoke.run(id, async () => {
            await this.#get_rpc().revoke({ session_id: id });
        });
        if (this.revoke.succeeded(id))
            await this.fetch();
    }
    async submit_revoke_all() {
        await this.revoke_all.run(async () => {
            await this.#get_rpc().revoke_all();
        });
        if (this.revoke_all.succeeded) {
            // Current session is now revoked — next API call will 401.
            // Clear the local sessions cache so the UI shows the login page.
            this.sessions = [];
        }
    }
}
