/**
 * rNotes Automerge document schemas — Vault Browser.
 *
 * rNotes is now a vault sync + browse module for Obsidian/Logseq vaults.
 * Rich editing moved to rDocs.
 *
 * DocId format: {space}:rnotes:vaults:{vaultId}
 *
 * Storage model:
 * - Automerge stores metadata (title, tags, hash, sync status)
 * - ZIP vault files stored on disk at /data/files/uploads/vaults/
 * - Content served on demand from ZIP (not stored in CRDT)
 */

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

// ── Vault note metadata (no content — lightweight) ──

export interface VaultNoteMeta {
	path: string;              // relative path within vault (e.g. "daily/2026-04-10.md")
	title: string;
	tags: string[];
	contentHash: string;       // SHA-256 of file content for change detection
	sizeBytes: number;
	lastModifiedAt: number;    // file mtime from vault
	syncStatus: 'synced' | 'local-modified' | 'conflict';
	frontmatter?: Record<string, any>; // parsed YAML frontmatter
	visibility?: import('../../shared/membrane').ObjectVisibility;
}

export interface VaultMeta {
	id: string;
	name: string;
	source: 'obsidian' | 'logseq';
	totalNotes: number;
	totalSizeBytes: number;
	lastSyncedAt: number;
	createdAt: number;
}

export interface VaultDoc {
	meta: {
		module: string;
		collection: string;
		version: number;
		spaceSlug: string;
		createdAt: number;
	};
	vault: VaultMeta;
	notes: Record<string, VaultNoteMeta>;       // keyed by path
	wikilinks: Record<string, string[]>;         // outgoing links per path
}

// ── Schema registration ──

export const vaultSchema: DocSchema<VaultDoc> = {
	module: 'rnotes',
	collection: 'vaults',
	version: 1,
	init: (): VaultDoc => ({
		meta: {
			module: 'rnotes',
			collection: 'vaults',
			version: 1,
			spaceSlug: '',
			createdAt: Date.now(),
		},
		vault: {
			id: '',
			name: 'Untitled Vault',
			source: 'obsidian',
			totalNotes: 0,
			totalSizeBytes: 0,
			lastSyncedAt: Date.now(),
			createdAt: Date.now(),
		},
		notes: {},
		wikilinks: {},
	}),
	migrate: (doc: VaultDoc, _fromVersion: number): VaultDoc => doc,
};

// ── Helpers ──

/** Generate a docId for a vault. */
export function vaultDocId(space: string, vaultId: string) {
	return `${space}:rnotes:vaults:${vaultId}` as const;
}

// ── Legacy re-exports for backward compat ──
// The old rNotes schemas (NotebookDoc, NoteItem, etc.) are now in rdocs/schemas.
// Converters and MCP tools that still import from here should be updated.
// For now, re-export from rdocs to avoid breaking shared/converters/types.ts.

export type { NoteItem, SourceRef } from '../rdocs/schemas';
