/**
 * CRDT Token Ledger — Automerge document schemas.
 *
 * Stores token definitions and ledger entries as Automerge CRDTs.
 * DocId format: global:tokens:ledgers:{tokenId}
 */

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

// ── Document types ──

export interface LedgerEntry {
	id: string;
	to: string;
	toLabel: string;
	amount: number;
	memo: string;
	type: 'mint' | 'transfer' | 'burn';
	from: string;
	timestamp: number;
	issuedBy: string;
	txHash?: string;
	onChainNetwork?: string;
	/** Off-ramp ID for escrow burns */
	offRampId?: string;
	/** Escrow status: 'escrow' → 'confirmed' | 'reversed' */
	status?: 'escrow' | 'confirmed' | 'reversed';
}

export interface TokenDefinition {
	id: string;
	name: string;
	symbol: string;
	decimals: number;
	description: string;
	totalSupply: number;
	icon: string;
	color: string;
	createdAt: number;
	createdBy: string;
}

export interface TokenLedgerDoc {
	meta: {
		module: string;
		collection: string;
		version: number;
		spaceSlug: string;
		createdAt: number;
	};
	token: TokenDefinition;
	entries: Record<string, LedgerEntry>;
}

// ── Schema registration ──

export const tokenLedgerSchema: DocSchema<TokenLedgerDoc> = {
	module: 'tokens',
	collection: 'ledgers',
	version: 1,
	init: (): TokenLedgerDoc => ({
		meta: {
			module: 'tokens',
			collection: 'ledgers',
			version: 1,
			spaceSlug: 'global',
			createdAt: Date.now(),
		},
		token: {
			id: '',
			name: '',
			symbol: '',
			decimals: 6,
			description: '',
			totalSupply: 0,
			icon: '',
			color: '',
			createdAt: Date.now(),
			createdBy: '',
		},
		entries: {},
	}),
};

// ── Helpers ──

export function tokenDocId(tokenId: string) {
	return `global:tokens:ledgers:${tokenId}` as const;
}
