/**
 * rCal Local-First Client
 *
 * Wraps the shared local-first stack into a calendar-specific API.
 * External iCal sync stays server-side.
 */

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 { calendarSchema, calendarDocId } from './schemas';
import type { CalendarDoc, CalendarEvent, CalendarSource } from './schemas';

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

	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('cal', 'events');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) {
			this.#documents.open<CalendarDoc>(docId, calendarSchema, 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('[CalClient] Working offline'); }
		this.#initialized = true;
	}

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

	getCalendar(): CalendarDoc | undefined {
		return this.#documents.get<CalendarDoc>(calendarDocId(this.#space) as DocumentId);
	}

	updateEvent(eventId: string, changes: Partial<CalendarEvent>): void {
		const docId = calendarDocId(this.#space) as DocumentId;
		this.#sync.change<CalendarDoc>(docId, `Update event ${eventId}`, (d) => {
			if (!d.events[eventId]) {
				d.events[eventId] = { id: eventId, title: '', description: '', startTime: 0, endTime: 0, allDay: false, timezone: null, rrule: null, status: null, visibility: null, sourceId: null, sourceName: null, sourceType: null, sourceColor: null, locationId: null, locationName: null, coordinates: null, locationGranularity: null, locationLat: null, locationLng: null, locationBreadcrumb: null, bookingStatus: null, isVirtual: false, virtualUrl: null, virtualPlatform: null, rToolSource: null, rToolEntityId: null, attendees: [], attendeeCount: 0, metadata: null, createdAt: Date.now(), updatedAt: Date.now(), ...changes } as CalendarEvent;
			} else {
				Object.assign(d.events[eventId], changes);
				d.events[eventId].updatedAt = Date.now();
			}
		});
	}

	deleteEvent(eventId: string): void {
		const docId = calendarDocId(this.#space) as DocumentId;
		this.#sync.change<CalendarDoc>(docId, `Delete event ${eventId}`, (d) => { delete d.events[eventId]; });
	}

	onChange(cb: (doc: CalendarDoc) => void): () => void {
		return this.#sync.onChange(calendarDocId(this.#space) 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();
	}
}
