/**
 * rMaps Local-First Client — persistent annotations, routes, meeting points.
 */

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 { mapsSchema, mapsDocId } from './schemas';
import type { MapsDoc, MapAnnotation, SavedRoute, SavedMeetingPoint, MapChatMessage } from './schemas';

export class MapsLocalFirstClient {
	#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(mapsSchema);
	}

	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('maps', 'annotations');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) this.#documents.open<MapsDoc>(docId, mapsSchema, 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<MapsDoc | null> {
		const docId = mapsDocId(this.#space) as DocumentId;
		let doc = this.#documents.get<MapsDoc>(docId);
		if (!doc) { const b = await this.#store.load(docId); doc = b ? this.#documents.open<MapsDoc>(docId, mapsSchema, b) : this.#documents.open<MapsDoc>(docId, mapsSchema); }
		await this.#sync.subscribe([docId]); return doc ?? null;
	}

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

	addAnnotation(annotation: MapAnnotation): void {
		this.#sync.change<MapsDoc>(mapsDocId(this.#space) as DocumentId, `Add ${annotation.type}`, (d) => { d.annotations[annotation.id] = annotation; });
	}
	removeAnnotation(id: string): void {
		this.#sync.change<MapsDoc>(mapsDocId(this.#space) as DocumentId, `Remove annotation`, (d) => { delete d.annotations[id]; });
	}
	saveRoute(route: SavedRoute): void {
		this.#sync.change<MapsDoc>(mapsDocId(this.#space) as DocumentId, `Save route ${route.name}`, (d) => { d.savedRoutes[route.id] = route; });
	}
	deleteRoute(id: string): void {
		this.#sync.change<MapsDoc>(mapsDocId(this.#space) as DocumentId, `Delete route`, (d) => { delete d.savedRoutes[id]; });
	}
	setMeetingPoint(point: SavedMeetingPoint): void {
		this.#sync.change<MapsDoc>(mapsDocId(this.#space) as DocumentId, `Set meeting point`, (d) => { d.savedMeetingPoints[point.id] = point; });
	}
	removeMeetingPoint(id: string): void {
		this.#sync.change<MapsDoc>(mapsDocId(this.#space) as DocumentId, `Remove meeting point`, (d) => { delete d.savedMeetingPoints[id]; });
	}
	addMessage(msg: MapChatMessage): void {
		this.#sync.change<MapsDoc>(mapsDocId(this.#space) as DocumentId, `Chat message`, (d) => { d.messages[msg.id] = msg; });
	}
	deleteMessage(id: string): void {
		this.#sync.change<MapsDoc>(mapsDocId(this.#space) as DocumentId, `Delete message`, (d) => { delete d.messages[id]; });
	}

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