/**
 * rTrips Local-First Client
 *
 * Wraps the shared local-first stack into a trips-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 { tripSchema, tripDocId } from './schemas';
import type { TripDoc, TripMeta, Destination, ItineraryItem, Booking, Expense, PackingItem } from './schemas';

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

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

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

	getTrip(tripId: string): TripDoc | undefined {
		return this.#documents.get<TripDoc>(tripDocId(this.#space, tripId) as DocumentId);
	}

	updateTrip(tripId: string, changes: Partial<TripMeta>): void {
		const docId = tripDocId(this.#space, tripId) as DocumentId;
		this.#sync.change<TripDoc>(docId, 'Update trip', (d) => {
			Object.assign(d.trip, changes);
			d.trip.updatedAt = Date.now();
		});
	}

	addDestination(tripId: string, dest: Destination): void {
		const docId = tripDocId(this.#space, tripId) as DocumentId;
		this.#sync.change<TripDoc>(docId, `Add destination ${dest.id}`, (d) => { d.destinations[dest.id] = dest; });
	}

	addItineraryItem(tripId: string, item: ItineraryItem): void {
		const docId = tripDocId(this.#space, tripId) as DocumentId;
		this.#sync.change<TripDoc>(docId, `Add itinerary ${item.id}`, (d) => { d.itinerary[item.id] = item; });
	}

	addBooking(tripId: string, booking: Booking): void {
		const docId = tripDocId(this.#space, tripId) as DocumentId;
		this.#sync.change<TripDoc>(docId, `Add booking ${booking.id}`, (d) => { d.bookings[booking.id] = booking; });
	}

	addExpense(tripId: string, expense: Expense): void {
		const docId = tripDocId(this.#space, tripId) as DocumentId;
		this.#sync.change<TripDoc>(docId, `Add expense ${expense.id}`, (d) => { d.expenses[expense.id] = expense; });
	}

	addPackingItem(tripId: string, item: PackingItem): void {
		const docId = tripDocId(this.#space, tripId) as DocumentId;
		this.#sync.change<TripDoc>(docId, `Add packing ${item.id}`, (d) => { d.packingItems[item.id] = item; });
	}

	togglePacked(tripId: string, itemId: string, packed: boolean): void {
		const docId = tripDocId(this.#space, tripId) as DocumentId;
		this.#sync.change<TripDoc>(docId, `Toggle packed ${itemId}`, (d) => {
			if (d.packingItems[itemId]) d.packingItems[itemId].packed = packed;
		});
	}

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