/**
 * rFlows Automerge document schemas.
 *
 * Granularity: one Automerge document per space (flow associations).
 * DocId format: {space}:flows:data
 *
 * v1: space-flow associations only
 * v2: adds canvasFlows (full node data) and activeFlowId
 */

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

// ── Document types ──

export interface SpaceFlow {
	id: string;
	spaceSlug: string;
	flowId: string;
	addedBy: string | null;
	createdAt: number;
}

export interface CanvasFlow {
	id: string;
	name: string;
	nodes: FlowNode[];
	createdAt: number;
	updatedAt: number;
	createdBy: string | null;
}

export interface FlowsDoc {
	meta: {
		module: string;
		collection: string;
		version: number;
		spaceSlug: string;
		createdAt: number;
	};
	spaceFlows: Record<string, SpaceFlow>;
	canvasFlows: Record<string, CanvasFlow>;
	activeFlowId: string;
}

// ── Schema registration ──

export const flowsSchema: DocSchema<FlowsDoc> = {
	module: 'flows',
	collection: 'data',
	version: 2,
	init: (): FlowsDoc => ({
		meta: {
			module: 'flows',
			collection: 'data',
			version: 2,
			spaceSlug: '',
			createdAt: Date.now(),
		},
		spaceFlows: {},
		canvasFlows: {},
		activeFlowId: '',
	}),
	migrate: (doc: any, _fromVersion: number) => {
		if (!doc.canvasFlows) doc.canvasFlows = {};
		if (!doc.activeFlowId) doc.activeFlowId = '';
		doc.meta.version = 2;
		return doc;
	},
};

// ── Helpers ──

export function flowsDocId(space: string) {
	return `${space}:flows:data` as const;
}
