/**
 * rPhotos Local-First Client
 *
 * Syncs shared album curation and photo annotations.
 */

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 { photosSchema, photosDocId } from './schemas';
import type { PhotosDoc, SharedAlbum, PhotoAnnotation } from './schemas';

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

	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('photos', 'albums');
		const cached = await this.#store.loadMany(cachedIds);
		for (const [docId, binary] of cached) this.#documents.open<PhotosDoc>(docId, photosSchema, 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('[PhotosClient] Working offline'); }
		this.#initialized = true;
	}

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

	getDoc(): PhotosDoc | undefined { return this.#documents.get<PhotosDoc>(photosDocId(this.#space) as DocumentId); }
	onChange(cb: (doc: PhotosDoc) => void): () => void { return this.#sync.onChange(photosDocId(this.#space) as DocumentId, cb as (doc: any) => void); }

	shareAlbum(album: SharedAlbum): void {
		const docId = photosDocId(this.#space) as DocumentId;
		this.#sync.change<PhotosDoc>(docId, `Share album ${album.name}`, (d) => { d.sharedAlbums[album.id] = album; });
	}

	unshareAlbum(albumId: string): void {
		const docId = photosDocId(this.#space) as DocumentId;
		this.#sync.change<PhotosDoc>(docId, `Unshare album`, (d) => { delete d.sharedAlbums[albumId]; });
	}

	annotatePhoto(annotation: PhotoAnnotation): void {
		const docId = photosDocId(this.#space) as DocumentId;
		this.#sync.change<PhotosDoc>(docId, `Annotate photo`, (d) => { d.annotations[annotation.assetId] = annotation; });
	}

	removeAnnotation(assetId: string): void {
		const docId = photosDocId(this.#space) as DocumentId;
		this.#sync.change<PhotosDoc>(docId, `Remove annotation`, (d) => { delete d.annotations[assetId]; });
	}

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