/**
 * rWallet Local-First Client
 *
 * Wraps the shared local-first stack for shared treasury management.
 */

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 { walletSchema, walletDocId } from './schemas';
import type { WalletDoc, WatchedAddress, TxAnnotation } from './schemas';

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

	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('wallet', 'treasury');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) {
			this.#documents.open<WalletDoc>(docId, walletSchema, 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('[WalletClient] Working offline'); }
		this.#initialized = true;
	}

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

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

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

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

	// ── Watchlist CRUD ──

	addWatchAddress(address: string, chain: string, label: string, addedBy: string | null): void {
		const docId = walletDocId(this.#space) as DocumentId;
		const key = `${chain}:${address.toLowerCase()}`;
		this.#sync.change<WalletDoc>(docId, `Watch ${label || address}`, (d) => {
			d.watchedAddresses[key] = { address, chain, label, addedBy, addedAt: Date.now() };
		});
	}

	removeWatchAddress(key: string): void {
		const docId = walletDocId(this.#space) as DocumentId;
		this.#sync.change<WalletDoc>(docId, `Unwatch address`, (d) => {
			delete d.watchedAddresses[key];
		});
	}

	// ── Annotations ──

	setAnnotation(txHash: string, note: string, authorDid: string): void {
		const docId = walletDocId(this.#space) as DocumentId;
		this.#sync.change<WalletDoc>(docId, `Annotate tx`, (d) => {
			d.annotations[txHash] = { txHash, note, authorDid, createdAt: Date.now() };
		});
	}

	removeAnnotation(txHash: string): void {
		const docId = walletDocId(this.#space) as DocumentId;
		this.#sync.change<WalletDoc>(docId, `Remove annotation`, (d) => {
			delete d.annotations[txHash];
		});
	}

	// ── Dashboard config ──

	updateConfig(config: Partial<{ defaultChain: string; displayCurrency: string; layout: string }>): void {
		const docId = walletDocId(this.#space) as DocumentId;
		this.#sync.change<WalletDoc>(docId, `Update config`, (d) => {
			if (config.defaultChain) d.dashboardConfig.defaultChain = config.defaultChain;
			if (config.displayCurrency) d.dashboardConfig.displayCurrency = config.displayCurrency;
			if (config.layout) d.dashboardConfig.layout = config.layout;
		});
	}

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