/**
 * rMeets Local-First Client — syncs meeting scheduling and history.
 */

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 { meetsSchema, meetsDocId } from './schemas';
import type { MeetsDoc, Meeting } from './schemas';

export class MeetsLocalFirstClient {
	#space: string; #documents: DocumentManager; #store: EncryptedDocStore; #sync: DocSyncManager; #initialized = false;

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

	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('meets', 'meetings');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) this.#documents.open<MeetsDoc>(docId, meetsSchema, binary);
		await this.#sync.preloadSyncStates(cachedIds);
		const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
		try { await this.#sync.connect(`${proto}//${location.host}/ws/${this.#space}`, this.#space); } catch {}
		this.#initialized = true;
	}

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

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

	scheduleMeeting(meeting: Meeting): void {
		this.#sync.change<MeetsDoc>(meetsDocId(this.#space) as DocumentId, `Schedule ${meeting.title}`, (d) => { d.meetings[meeting.id] = meeting; });
	}
	cancelMeeting(id: string): void {
		this.#sync.change<MeetsDoc>(meetsDocId(this.#space) as DocumentId, `Cancel meeting`, (d) => { delete d.meetings[id]; });
	}
	joinMeeting(meetingId: string, participantDid: string): void {
		this.#sync.change<MeetsDoc>(meetsDocId(this.#space) as DocumentId, `Join meeting`, (d) => {
			if (d.meetings[meetingId] && !d.meetings[meetingId].participants.includes(participantDid)) {
				d.meetings[meetingId].participants.push(participantDid);
			}
		});
	}

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