/**
 * rInbox Local-First Client
 *
 * Wraps the shared local-first stack into a mailbox-specific API.
 * IMAP sync stays server-side — Automerge holds thread/comment state.
 */

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 { mailboxSchema, mailboxDocId } from './schemas';
import type { MailboxDoc, ThreadItem } from './schemas';

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

	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('inbox', 'mailboxes');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) {
			this.#documents.open<MailboxDoc>(docId, mailboxSchema, 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('[InboxClient] Working offline'); }
		this.#initialized = true;
	}

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

	getMailbox(mailboxId: string): MailboxDoc | undefined {
		return this.#documents.get<MailboxDoc>(mailboxDocId(this.#space, mailboxId) as DocumentId);
	}

	updateThread(mailboxId: string, threadId: string, changes: Partial<ThreadItem>): void {
		const docId = mailboxDocId(this.#space, mailboxId) as DocumentId;
		this.#sync.change<MailboxDoc>(docId, `Update thread ${threadId}`, (d) => {
			if (d.threads[threadId]) {
				Object.assign(d.threads[threadId], changes);
			}
		});
	}

	onChange(mailboxId: string, cb: (doc: MailboxDoc) => void): () => void {
		return this.#sync.onChange(mailboxDocId(this.#space, mailboxId) 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();
	}
}
