/**
 * rMaps Automerge document schemas.
 *
 * Persistent map annotations, saved routes, and meeting points.
 * Ephemeral live location sharing remains via WebSocket rooms.
 *
 * DocId format: {space}:maps:annotations
 */

import type { DocSchema } from '../../shared/local-first/document';

export interface MapAnnotation {
	id: string;
	type: 'pin' | 'note' | 'area';
	lat: number;
	lng: number;
	label: string;
	authorDid: string | null;
	createdAt: number;
}

export interface SavedRoute {
	id: string;
	name: string;
	waypoints: { lat: number; lng: number; label?: string }[];
	authorDid: string | null;
	createdAt: number;
}

export interface SavedMeetingPoint {
	id: string;
	name: string;
	lat: number;
	lng: number;
	setBy: string | null;
	createdAt: number;
}

export interface MapChatMessage {
	id: string;
	authorId: string;
	authorName: string;
	authorEmoji: string;
	text: string;
	createdAt: number;
	replyToId?: string;
}

export interface MapsDoc {
	meta: { module: string; collection: string; version: number; spaceSlug: string; createdAt: number };
	annotations: Record<string, MapAnnotation>;
	savedRoutes: Record<string, SavedRoute>;
	savedMeetingPoints: Record<string, SavedMeetingPoint>;
	messages: Record<string, MapChatMessage>;
}

export const mapsSchema: DocSchema<MapsDoc> = {
	module: 'maps',
	collection: 'annotations',
	version: 2,
	init: (): MapsDoc => ({
		meta: { module: 'maps', collection: 'annotations', version: 2, spaceSlug: '', createdAt: Date.now() },
		annotations: {},
		savedRoutes: {},
		savedMeetingPoints: {},
		messages: {},
	}),
	migrate: (doc: any) => {
		if (!doc.annotations) doc.annotations = {};
		if (!doc.savedRoutes) doc.savedRoutes = {};
		if (!doc.savedMeetingPoints) doc.savedMeetingPoints = {};
		if (!doc.messages) doc.messages = {};
		doc.meta.version = 2;
		return doc;
	},
};

export function mapsDocId(space: string) { return `${space}:maps:annotations` as const; }
