/**
 * rForum Local-First Client — syncs forum provisioning state.
 */

import { DocumentManager } from '../../shared/local-first/document';
import type { DocumentId } from '../../shared/local-first/document';
import { EncryptedDocStore } from '../../shared/local-first/storage';
import { DocSyncManager } from '../../shared/local-first/sync';
import { DocCrypto } from '../../shared/local-first/crypto';
import { forumSchema, FORUM_DOC_ID } from './schemas';
import type { ForumDoc, ForumInstance } from './schemas';

export class ForumLocalFirstClient {
	#documents: DocumentManager;
	#store: EncryptedDocStore;
	#sync: DocSyncManager;
	#initialized = false;

	constructor(space: string, docCrypto?: DocCrypto) {
		this.#documents = new DocumentManager();
		this.#store = new EncryptedDocStore(space, docCrypto);
		this.#sync = new DocSyncManager({ documents: this.#documents, store: this.#store });
		this.#documents.registerSchema(forumSchema);
	}

	get isConnected(): boolean { return this.#sync.isConnected; }

	async init(): Promise<void> {
		if (this.#initialized) return;
		await this.#store.open();
		const cachedIds = await this.#store.listByModule('forum', 'instances');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) this.#documents.open<ForumDoc>(docId, forumSchema, binary);
		await this.#sync.preloadSyncStates(cachedIds);
		const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
		try { await this.#sync.connect(`${proto}//${location.host}/ws/global`, 'global'); } catch {}
		this.#initialized = true;
	}

	async subscribe(): Promise<ForumDoc | null> {
		const docId = FORUM_DOC_ID as DocumentId;
		let doc = this.#documents.get<ForumDoc>(docId);
		if (!doc) { const b = await this.#store.load(docId); doc = b ? this.#documents.open<ForumDoc>(docId, forumSchema, b) : this.#documents.open<ForumDoc>(docId, forumSchema); }
		await this.#sync.subscribe([docId]); return doc ?? null;
	}

	getDoc(): ForumDoc | undefined { return this.#documents.get<ForumDoc>(FORUM_DOC_ID as DocumentId); }
	onChange(cb: (doc: ForumDoc) => void): () => void { return this.#sync.onChange(FORUM_DOC_ID as DocumentId, cb as (doc: any) => void); }

	updateInstance(instance: ForumInstance): void {
		this.#sync.change<ForumDoc>(FORUM_DOC_ID as DocumentId, `Update ${instance.name}`, (d) => { d.instances[instance.id] = instance; });
	}

	async disconnect(): Promise<void> { await this.#sync.flush(); this.#sync.disconnect(); }
}
