/**
 * 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, shoppingCartSchema, shoppingCartIndexSchema,
	catalogDocId, orderDocId, shoppingCartDocId, shoppingCartIndexDocId,
} from './schemas';
import type { CatalogDoc, CatalogEntry, OrderDoc, ShoppingCartDoc, ShoppingCartIndexDoc } 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);
		this.#documents.registerSchema(shoppingCartSchema);
		this.#documents.registerSchema(shoppingCartIndexSchema);
	}

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

	async init(): Promise<void> {
		if (this.#initialized) return;
		await this.#store.open();
		const [catalogIds, orderIds, shoppingIds, shoppingIndexIds] = await Promise.all([
			this.#store.listByModule('cart', 'catalog'),
			this.#store.listByModule('cart', 'orders'),
			this.#store.listByModule('cart', 'shopping'),
			this.#store.listByModule('cart', 'shopping-index'),
		]);
		const allIds = [...catalogIds, ...orderIds, ...shoppingIds, ...shoppingIndexIds];
		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 if (shoppingIds.includes(docId)) {
				this.#documents.open<ShoppingCartDoc>(docId, shoppingCartSchema, binary);
			} else if (shoppingIndexIds.includes(docId)) {
				this.#documents.open<ShoppingCartIndexDoc>(docId, shoppingCartIndexSchema, 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);
	}

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

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

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

	onCartChange(cartId: string, cb: (doc: ShoppingCartDoc) => void): () => void {
		return this.#sync.onChange(shoppingCartDocId(this.#space, cartId) 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();
	}
}
