/**
 * rCal Automerge document schemas.
 *
 * Granularity: one Automerge document per space (all events + sources).
 * DocId format: {space}:cal:events
 */

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

// ── Document types ──

export interface CalendarSource {
	id: string;
	name: string;
	sourceType: string;
	url: string | null;
	color: string | null;
	isActive: boolean;
	isVisible: boolean;
	syncIntervalMinutes: number | null;
	lastSyncedAt: number;
	ownerId: string | null;
	createdAt: number;
}

export interface CalendarEvent {
	id: string;
	title: string;
	description: string;
	startTime: number;
	endTime: number;
	allDay: boolean;
	timezone: string | null;
	rrule: string | null;
	status: string | null;
	visibility: string | null;
	sourceId: string | null;
	sourceName: string | null;
	sourceType: string | null;
	sourceColor: string | null;
	locationId: string | null;
	locationName: string | null;
	coordinates: { x: number; y: number } | null;
	locationGranularity: string | null;
	locationLat: number | null;
	locationLng: number | null;
	isVirtual: boolean;
	virtualUrl: string | null;
	virtualPlatform: string | null;
	rToolSource: string | null;
	rToolEntityId: string | null;
	attendees: unknown[];
	attendeeCount: number;
	metadata: unknown | null;
	createdAt: number;
	updatedAt: number;
}

export interface CalendarDoc {
	meta: {
		module: string;
		collection: string;
		version: number;
		spaceSlug: string;
		createdAt: number;
	};
	sources: Record<string, CalendarSource>;
	events: Record<string, CalendarEvent>;
}

// ── Schema registration ──

export const calendarSchema: DocSchema<CalendarDoc> = {
	module: 'cal',
	collection: 'events',
	version: 1,
	init: (): CalendarDoc => ({
		meta: {
			module: 'cal',
			collection: 'events',
			version: 1,
			spaceSlug: '',
			createdAt: Date.now(),
		},
		sources: {},
		events: {},
	}),
};

// ── Helpers ──

export function calendarDocId(space: string) {
	return `${space}:cal:events` as const;
}
