/**
 * rWallet Automerge document schemas.
 *
 * Stores shared watchlist addresses, transaction annotations,
 * and dashboard configuration synced across space members.
 *
 * DocId format: {space}:wallet:treasury
 */

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

// ── Document types ──

export interface WatchedAddress {
	address: string;
	chain: string;
	label: string;
	addedBy: string | null;
	addedAt: number;
	visibility?: import('../../shared/membrane').ObjectVisibility;
}

export interface TxAnnotation {
	txHash: string;
	note: string;
	authorDid: string;
	createdAt: number;
}

export interface DashboardConfig {
	defaultChain: string;
	displayCurrency: string;
	layout: string;
}

export interface WalletDoc {
	meta: {
		module: string;
		collection: string;
		version: number;
		spaceSlug: string;
		createdAt: number;
	};
	watchedAddresses: Record<string, WatchedAddress>;
	annotations: Record<string, TxAnnotation>;
	dashboardConfig: DashboardConfig;
}

// ── Schema registration ──

export const walletSchema: DocSchema<WalletDoc> = {
	module: 'wallet',
	collection: 'treasury',
	version: 1,
	init: (): WalletDoc => ({
		meta: {
			module: 'wallet',
			collection: 'treasury',
			version: 1,
			spaceSlug: '',
			createdAt: Date.now(),
		},
		watchedAddresses: {},
		annotations: {},
		dashboardConfig: {
			defaultChain: '1',
			displayCurrency: 'USD',
			layout: 'grid',
		},
	}),
	migrate: (doc: any, _fromVersion: number) => {
		if (!doc.watchedAddresses) doc.watchedAddresses = {};
		if (!doc.annotations) doc.annotations = {};
		if (!doc.dashboardConfig) doc.dashboardConfig = { defaultChain: '1', displayCurrency: 'USD', layout: 'grid' };
		doc.meta.version = 1;
		return doc;
	},
};

// ── Helpers ──

export function walletDocId(space: string) {
	return `${space}:wallet:treasury` as const;
}
