/**
 * rPubs Local-First Client
 *
 * Wraps existing Automerge schemas for collaborative document editing.
 * Each draft is a separate Automerge doc with shared markdown content.
 */

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 { pubsDraftSchema, pubsDocId } from './schemas';
import type { PubsDoc, PubsDraftMeta } from './schemas';

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

	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('pubs', 'drafts');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) this.#documents.open<PubsDoc>(docId, pubsDraftSchema, 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('[PubsClient] Working offline'); }
		this.#initialized = true;
	}

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

	getDraft(draftId: string): PubsDoc | undefined {
		return this.#documents.get<PubsDoc>(pubsDocId(this.#space, draftId) as DocumentId);
	}

	onDraftChange(draftId: string, cb: (doc: PubsDoc) => void): () => void {
		return this.#sync.onChange(pubsDocId(this.#space, draftId) as DocumentId, cb as (doc: any) => void);
	}

	/** List all cached draft IDs */
	async listDrafts(): Promise<string[]> {
		return this.#store.listByModule('pubs', 'drafts');
	}

	// ── Draft CRUD ──

	updateContent(draftId: string, content: string): void {
		const docId = pubsDocId(this.#space, draftId) as DocumentId;
		this.#sync.change<PubsDoc>(docId, `Update content`, (d) => {
			d.content = content;
			d.draft.updatedAt = Date.now();
		});
	}

	updateMeta(draftId: string, meta: Partial<PubsDraftMeta>): void {
		const docId = pubsDocId(this.#space, draftId) as DocumentId;
		this.#sync.change<PubsDoc>(docId, `Update draft meta`, (d) => {
			if (meta.title !== undefined) d.draft.title = meta.title;
			if (meta.author !== undefined) d.draft.author = meta.author;
			if (meta.format !== undefined) d.draft.format = meta.format;
			d.draft.updatedAt = Date.now();
		});
	}

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