/**
 * rFlows 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 { flowsSchema, flowsDocId } from './schemas';
import type { FlowsDoc, SpaceFlow, CanvasFlow } from './schemas';
import type { FlowNode } from './lib/types';

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

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

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

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

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

	removeSpaceFlow(flowId: string): void {
		const docId = flowsDocId(this.#space) as DocumentId;
		this.#sync.change<FlowsDoc>(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: FlowsDoc) => void): () => void {
		return this.#sync.onChange(flowsDocId(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); }

	// ── Canvas flow CRUD ──

	listCanvasFlows(): CanvasFlow[] {
		const doc = this.getFlows();
		if (!doc?.canvasFlows) return [];
		return Object.values(doc.canvasFlows).sort((a, b) => b.updatedAt - a.updatedAt);
	}

	getCanvasFlow(id: string): CanvasFlow | undefined {
		const doc = this.getFlows();
		return doc?.canvasFlows?.[id];
	}

	saveCanvasFlow(flow: CanvasFlow): void {
		const docId = flowsDocId(this.#space) as DocumentId;
		this.#sync.change<FlowsDoc>(docId, `Save canvas flow ${flow.name}`, (d) => {
			if (!d.canvasFlows) d.canvasFlows = {} as any;
			flow.updatedAt = Date.now();
			d.canvasFlows[flow.id] = flow;
		});
	}

	updateFlowNodes(flowId: string, nodes: FlowNode[]): void {
		const docId = flowsDocId(this.#space) as DocumentId;
		this.#sync.change<FlowsDoc>(docId, `Update flow nodes`, (d) => {
			const flow = d.canvasFlows?.[flowId];
			if (flow) {
				flow.nodes = nodes as any;
				flow.updatedAt = Date.now();
			}
		});
	}

	renameCanvasFlow(flowId: string, name: string): void {
		const docId = flowsDocId(this.#space) as DocumentId;
		this.#sync.change<FlowsDoc>(docId, `Rename flow to ${name}`, (d) => {
			const flow = d.canvasFlows?.[flowId];
			if (flow) {
				flow.name = name;
				flow.updatedAt = Date.now();
			}
		});
	}

	deleteCanvasFlow(flowId: string): void {
		const docId = flowsDocId(this.#space) as DocumentId;
		this.#sync.change<FlowsDoc>(docId, `Delete canvas flow`, (d) => {
			if (d.canvasFlows?.[flowId]) delete d.canvasFlows[flowId];
			if (d.activeFlowId === flowId) d.activeFlowId = '';
		});
	}

	setActiveFlow(flowId: string): void {
		const docId = flowsDocId(this.#space) as DocumentId;
		this.#sync.change<FlowsDoc>(docId, `Set active flow`, (d) => {
			d.activeFlowId = flowId;
		});
	}

	getActiveFlowId(): string {
		const doc = this.getFlows();
		return doc?.activeFlowId || '';
	}

	// ── Budget CRUD ──

	saveBudgetAllocation(did: string, allocations: Record<string, number>): void {
		const docId = flowsDocId(this.#space) as DocumentId;
		this.#sync.change<FlowsDoc>(docId, `Save budget allocation`, (d) => {
			if (!d.budgetAllocations) d.budgetAllocations = {} as any;
			d.budgetAllocations[did] = {
				participantDid: did,
				allocations,
				updatedAt: Date.now(),
			};
		});
	}

	addBudgetSegment(id: string, name: string, color: string, createdBy: string | null): void {
		const docId = flowsDocId(this.#space) as DocumentId;
		this.#sync.change<FlowsDoc>(docId, `Add budget segment ${name}`, (d) => {
			if (!d.budgetSegments) d.budgetSegments = {} as any;
			d.budgetSegments[id] = { name, color, createdBy };
			// Initialize all existing allocations with 0 for new segment
			if (d.budgetAllocations) {
				for (const alloc of Object.values(d.budgetAllocations)) {
					if (!alloc.allocations[id]) alloc.allocations[id] = 0;
				}
			}
		});
	}

	removeBudgetSegment(id: string): void {
		const docId = flowsDocId(this.#space) as DocumentId;
		this.#sync.change<FlowsDoc>(docId, `Remove budget segment`, (d) => {
			if (d.budgetSegments?.[id]) delete d.budgetSegments[id];
			// Clean allocations
			if (d.budgetAllocations) {
				for (const alloc of Object.values(d.budgetAllocations)) {
					if (alloc.allocations[id] !== undefined) delete alloc.allocations[id];
				}
			}
		});
	}

	setBudgetTotalAmount(amount: number): void {
		const docId = flowsDocId(this.#space) as DocumentId;
		this.#sync.change<FlowsDoc>(docId, `Set budget total`, (d) => {
			d.budgetTotalAmount = amount;
		});
	}

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