/**
 * rChoices Local-First Client
 *
 * Wraps the shared local-first stack for collaborative voting sessions.
 */

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 { choicesSchema, choicesDocId } from './schemas';
import type { ChoicesDoc, ChoiceSession, ChoiceVote, ChoiceOption } from './schemas';

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

	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('choices', 'sessions');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) {
			this.#documents.open<ChoicesDoc>(docId, choicesSchema, 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('[ChoicesClient] Working offline'); }
		this.#initialized = true;
	}

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

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

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

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

	// ── Session CRUD ──

	createSession(session: ChoiceSession): void {
		const docId = choicesDocId(this.#space) as DocumentId;
		this.#sync.change<ChoicesDoc>(docId, `Create session ${session.title}`, (d) => {
			d.sessions[session.id] = session;
		});
	}

	closeSession(sessionId: string): void {
		const docId = choicesDocId(this.#space) as DocumentId;
		this.#sync.change<ChoicesDoc>(docId, `Close session`, (d) => {
			if (d.sessions[sessionId]) d.sessions[sessionId].closed = true;
		});
	}

	deleteSession(sessionId: string): void {
		const docId = choicesDocId(this.#space) as DocumentId;
		this.#sync.change<ChoicesDoc>(docId, `Delete session`, (d) => {
			delete d.sessions[sessionId];
			// Clean up votes for this session
			for (const key of Object.keys(d.votes)) {
				if (key.startsWith(`${sessionId}:`)) delete d.votes[key];
			}
		});
	}

	// ── Voting ──

	castVote(sessionId: string, participantDid: string, choices: Record<string, number>): void {
		const docId = choicesDocId(this.#space) as DocumentId;
		const voteKey = `${sessionId}:${participantDid}`;
		this.#sync.change<ChoicesDoc>(docId, `Cast vote`, (d) => {
			d.votes[voteKey] = {
				participantDid,
				choices,
				updatedAt: Date.now(),
			};
		});
	}

	getVotesForSession(sessionId: string): ChoiceVote[] {
		const doc = this.getDoc();
		if (!doc?.votes) return [];
		return Object.entries(doc.votes)
			.filter(([key]) => key.startsWith(`${sessionId}:`))
			.map(([, vote]) => vote);
	}

	getMyVote(sessionId: string, myDid: string): ChoiceVote | null {
		const doc = this.getDoc();
		return doc?.votes?.[`${sessionId}:${myDid}`] ?? null;
	}

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