/**
 * rCart Local-First Client
 *
 * Wraps the shared local-first stack into a cart-specific API.
 * Orders use Intent/Claim — server validates pricing and fulfillment.
 */

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 { catalogSchema, orderSchema, catalogDocId, orderDocId } from './schemas';
import type { CatalogDoc, CatalogEntry, OrderDoc } from './schemas';

export class CartLocalFirstClient {
	#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(catalogSchema);
		this.#documents.registerSchema(orderSchema);
	}

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

	async init(): Promise<void> {
		if (this.#initialized) return;
		await this.#store.open();
		const [catalogIds, orderIds] = await Promise.all([
			this.#store.listByModule('cart', 'catalog'),
			this.#store.listByModule('cart', 'orders'),
		]);
		const allIds = [...catalogIds, ...orderIds];
		const cached = await this.#store.loadMany(allIds);
		for (const [docId, binary] of cached) {
			if (catalogIds.includes(docId)) {
				this.#documents.open<CatalogDoc>(docId, catalogSchema, binary);
			} else {
				this.#documents.open<OrderDoc>(docId, orderSchema, binary);
			}
		}
		await this.#sync.preloadSyncStates(allIds);
		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('[CartClient] Working offline'); }
		this.#initialized = true;
	}

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

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

	getCatalog(): CatalogDoc | undefined {
		return this.#documents.get<CatalogDoc>(catalogDocId(this.#space) as DocumentId);
	}

	onChange(cb: (doc: CatalogDoc) => void): () => void {
		return this.#sync.onChange(catalogDocId(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();
	}
}
