/**
 * rBnb Local-First Client
 *
 * Wraps the shared local-first stack into a hospitality-specific API.
 * Handles Automerge document sync for listings, stays, and endorsements.
 */

import * as Automerge from '@automerge/automerge';
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 { bnbSchema, bnbDocId } from './schemas';
import type { BnbDoc, Listing, StayRequest, StayMessage } from './schemas';

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

	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('bnb', 'listings');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) {
			this.#documents.open<BnbDoc>(docId, bnbSchema, binary);
		}
		await this.#sync.preloadSyncStates(cachedIds);
		const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
		const wsUrl = `${proto}//${location.host}/ws/${this.#space}`;
		try { await this.#sync.connect(wsUrl, this.#space); } catch { console.warn('[BnbClient] Working offline'); }
		this.#initialized = true;
	}

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

	getDoc(): BnbDoc | undefined {
		return this.#documents.get<BnbDoc>(bnbDocId(this.#space) as DocumentId);
	}

	updateListing(listingId: string, changes: Partial<Listing>): void {
		const docId = bnbDocId(this.#space) as DocumentId;
		this.#sync.change<BnbDoc>(docId, `Update listing ${listingId}`, (d) => {
			if (!d.listings[listingId]) return;
			Object.assign(d.listings[listingId], changes);
			d.listings[listingId].updatedAt = Date.now();
		});
	}

	createStayRequest(stay: Omit<StayRequest, 'id' | 'requestedAt' | 'respondedAt' | 'completedAt' | 'cancelledAt'>): string {
		const docId = bnbDocId(this.#space) as DocumentId;
		const stayId = crypto.randomUUID();
		this.#sync.change<BnbDoc>(docId, `Create stay ${stayId}`, (d) => {
			d.stays[stayId] = {
				...stay,
				id: stayId,
				requestedAt: Date.now(),
				respondedAt: null,
				completedAt: null,
				cancelledAt: null,
			};
		});
		return stayId;
	}

	addMessage(stayId: string, message: Omit<StayMessage, 'id' | 'sentAt'>): void {
		const docId = bnbDocId(this.#space) as DocumentId;
		this.#sync.change<BnbDoc>(docId, `Add message to stay ${stayId}`, (d) => {
			if (!d.stays[stayId]) return;
			d.stays[stayId].messages.push({
				...message,
				id: crypto.randomUUID(),
				sentAt: Date.now(),
			});
		});
	}

	onChange(cb: (doc: BnbDoc) => void): () => void {
		return this.#sync.onChange(bnbDocId(this.#space) as DocumentId, cb as (doc: any) => void);
	}

	onConnect(cb: () => void): () => void { return this.#sync.onConnect(cb); }
	onDisconnect(cb: () => void): () => void { return this.#sync.onDisconnect(cb); }

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