/**
 * rSheets Automerge document schemas.
 *
 * Granularity: one Automerge document per sheet.
 * DocId format: {space}:sheet:sheets:{sheetId}
 */

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

// ── Document types ──

export interface Cell {
	value: string;
	formula: string | null;
	format: string | null;
	updatedAt: number;
}

export interface ColConfig {
	label: string;
	width: number;
	type: string | null;
}

export interface RowConfig {
	height: number;
	hidden: boolean;
}

export interface SheetMeta {
	id: string;
	name: string;
	description: string;
	createdBy: string | null;
	createdAt: number;
	updatedAt: number;
}

export interface SheetDoc {
	meta: {
		module: string;
		collection: string;
		version: number;
		spaceSlug: string;
		createdAt: number;
	};
	sheet: SheetMeta;
	cells: Record<string, Cell>;
	columns: Record<string, ColConfig>;
	rows: Record<string, RowConfig>;
}

// ── Schema registration ──

export const sheetSchema: DocSchema<SheetDoc> = {
	module: 'sheet',
	collection: 'sheets',
	version: 1,
	init: (): SheetDoc => ({
		meta: {
			module: 'sheet',
			collection: 'sheets',
			version: 1,
			spaceSlug: '',
			createdAt: Date.now(),
		},
		sheet: {
			id: '',
			name: 'Untitled Sheet',
			description: '',
			createdBy: null,
			createdAt: Date.now(),
			updatedAt: Date.now(),
		},
		cells: {},
		columns: {},
		rows: {},
	}),
};

// ── Helpers ──

export function sheetDocId(space: string, sheetId: string) {
	return `${space}:sheet:sheets:${sheetId}` as const;
}
