/**
 * rSwag Local-First Client
 *
 * Wraps the shared local-first stack for collaborative design 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 { swagSchema, swagDocId } from './schemas';
import type { SwagDoc, SwagDesign } from './schemas';

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

	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('swag', 'designs');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) {
			this.#documents.open<SwagDoc>(docId, swagSchema, 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('[SwagClient] Working offline'); }
		this.#initialized = true;
	}

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

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

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

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

	// ── Design CRUD ──

	saveDesign(design: SwagDesign): void {
		const docId = swagDocId(this.#space) as DocumentId;
		this.#sync.change<SwagDoc>(docId, `Save design ${design.title}`, (d) => {
			d.designs[design.id] = design;
		});
	}

	updateDesignArtifact(designId: string, artifactId: string): void {
		const docId = swagDocId(this.#space) as DocumentId;
		this.#sync.change<SwagDoc>(docId, `Link artifact`, (d) => {
			if (d.designs[designId]) {
				d.designs[designId].artifactId = artifactId;
				d.designs[designId].updatedAt = Date.now();
			}
		});
	}

	deleteDesign(designId: string): void {
		const docId = swagDocId(this.#space) as DocumentId;
		this.#sync.change<SwagDoc>(docId, `Delete design`, (d) => {
			delete d.designs[designId];
			if (d.activeDesignId === designId) d.activeDesignId = null;
		});
	}

	setActiveDesign(designId: string | null): void {
		const docId = swagDocId(this.#space) as DocumentId;
		this.#sync.change<SwagDoc>(docId, `Set active design`, (d) => {
			d.activeDesignId = designId;
		});
	}

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