/**
 * rTasks Local-First Client
 *
 * Wraps the shared local-first stack into a tasks/kanban-specific API.
 */

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 { boardSchema, boardDocId } from './schemas';
import type { BoardDoc, TaskItem, BoardMeta } from './schemas';

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

	get isConnected(): boolean { return this.#sync.isConnected; }
	get isInitialized(): boolean { return this.#initialized; }

	async init(): Promise<void> {
		if (this.#initialized) return;
		await this.#store.open();
		const cachedIds = await this.#store.listByModule('tasks', 'boards');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) {
			this.#documents.open<BoardDoc>(docId, boardSchema, 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('[TasksClient] Working offline'); }
		this.#initialized = true;
	}

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

	getBoard(boardId: string): BoardDoc | undefined {
		return this.#documents.get<BoardDoc>(boardDocId(this.#space, boardId) as DocumentId);
	}

	updateTask(boardId: string, taskId: string, changes: Partial<TaskItem>): void {
		const docId = boardDocId(this.#space, boardId) as DocumentId;
		this.#sync.change<BoardDoc>(docId, `Update task ${taskId}`, (d) => {
			if (!d.tasks[taskId]) {
				d.tasks[taskId] = { id: taskId, spaceId: boardId, title: '', description: '', status: 'TODO', priority: null, labels: [], assigneeId: null, createdBy: null, sortOrder: 0, dueDate: null, createdAt: Date.now(), updatedAt: Date.now(), ...changes };
			} else {
				Object.assign(d.tasks[taskId], changes);
				d.tasks[taskId].updatedAt = Date.now();
			}
		});
	}

	deleteTask(boardId: string, taskId: string): void {
		const docId = boardDocId(this.#space, boardId) as DocumentId;
		this.#sync.change<BoardDoc>(docId, `Delete task ${taskId}`, (d) => { delete d.tasks[taskId]; });
	}

	updateBoard(boardId: string, changes: Partial<BoardMeta>): void {
		const docId = boardDocId(this.#space, boardId) as DocumentId;
		this.#sync.change<BoardDoc>(docId, 'Update board', (d) => {
			Object.assign(d.board, changes);
			d.board.updatedAt = Date.now();
		});
	}

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