/**
 * rNetwork Automerge document schemas.
 *
 * Stores CRM relationship metadata for collaborative network management.
 * Delegations remain in PostgreSQL (trust-engine); this doc syncs
 * contact info, relationship notes, and graph layout positions.
 *
 * DocId format: {space}:network:crm
 */

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

// ── Document types ──

export interface CrmContact {
	did: string;
	name: string;
	role: string;
	tags: string[];
	addedBy: string | null;
	addedAt: number;
}

export interface CrmRelationship {
	fromDid: string;
	toDid: string;
	type: string;
	weight: number;
	note: string;
}

export interface GraphLayout {
	positions: Record<string, { x: number; y: number }>;
	zoom: number;
	panX: number;
	panY: number;
}

export interface LayerConfig {
	moduleId: string;
	moduleName: string;
	moduleIcon: string;
	axis: string;
}

export interface CrossLayerFlowConfig {
	id: string;
	sourceLayerIdx: number;
	sourceFeedId: string;
	targetLayerIdx: number;
	targetFeedId: string;
	kind: string;
	strength: number;
}

export interface NetworkDoc {
	meta: {
		module: string;
		collection: string;
		version: number;
		spaceSlug: string;
		createdAt: number;
	};
	contacts: Record<string, CrmContact>;
	relationships: Record<string, CrmRelationship>;
	graphLayout: GraphLayout;
	layerConfigs: LayerConfig[];
	crossLayerFlowConfigs: CrossLayerFlowConfig[];
}

// ── Schema registration ──

export const networkSchema: DocSchema<NetworkDoc> = {
	module: 'network',
	collection: 'crm',
	version: 2,
	init: (): NetworkDoc => ({
		meta: {
			module: 'network',
			collection: 'crm',
			version: 2,
			spaceSlug: '',
			createdAt: Date.now(),
		},
		contacts: {},
		relationships: {},
		graphLayout: { positions: {}, zoom: 1, panX: 0, panY: 0 },
		layerConfigs: [],
		crossLayerFlowConfigs: [],
	}),
	migrate: (doc: any, _fromVersion: number) => {
		if (!doc.contacts) doc.contacts = {};
		if (!doc.relationships) doc.relationships = {};
		if (!doc.graphLayout) doc.graphLayout = { positions: {}, zoom: 1, panX: 0, panY: 0 };
		if (!doc.layerConfigs) doc.layerConfigs = [];
		if (!doc.crossLayerFlowConfigs) doc.crossLayerFlowConfigs = [];
		doc.meta.version = 2;
		return doc;
	},
};

// ── Helpers ──

export function networkDocId(space: string) {
	return `${space}:network:crm` as const;
}
