/**
 * rFunds Local-First Client
 *
 * Wraps the shared local-first stack for space-flow associations.
 * Actual flow logic stays in the external payment-flow service.
 */

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 { fundsSchema, fundsDocId } from './schemas';
import type { FundsDoc, SpaceFlow } from './schemas';

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

	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('funds', 'flows');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) {
			this.#documents.open<FundsDoc>(docId, fundsSchema, 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('[FundsClient] Working offline'); }
		this.#initialized = true;
	}

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

	getFlows(): FundsDoc | undefined {
		return this.#documents.get<FundsDoc>(fundsDocId(this.#space) as DocumentId);
	}

	addSpaceFlow(flow: SpaceFlow): void {
		const docId = fundsDocId(this.#space) as DocumentId;
		this.#sync.change<FundsDoc>(docId, `Add flow ${flow.flowId}`, (d) => {
			d.spaceFlows[flow.id] = flow;
		});
	}

	removeSpaceFlow(flowId: string): void {
		const docId = fundsDocId(this.#space) as DocumentId;
		this.#sync.change<FundsDoc>(docId, `Remove flow ${flowId}`, (d) => {
			for (const [id, sf] of Object.entries(d.spaceFlows)) {
				if (sf.flowId === flowId) delete d.spaceFlows[id];
			}
		});
	}

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