import { serializeTransaction, validateTransaction } from '../core/ledger';
import type { LedgerIndex, TransactionDraft } from '../core/types';

export interface MobileCommit {
  content: string;
  diff: string;
  sourceEventIds?: string[];
}

export function commitMobileTransaction(
  draft: TransactionDraft,
  ledger: LedgerIndex,
  currentMobileBean: string,
): MobileCommit {
  const result = validateTransaction(draft, ledger);
  if (!result.valid) throw new Error(result.errors.join('\n'));
  const diff = serializeTransaction(draft);
  const separator = currentMobileBean.trim() ? '\n\n' : '';
  return {
    content: `${currentMobileBean.trimEnd()}${separator}${diff}`,
    diff,
    sourceEventIds: draft.sourceEventIds,
  };
}

export function exportLedgerBundle(
  ledger: LedgerIndex,
  mainBean: string,
): Record<string, string> {
  return Object.fromEntries(
    [
      ...ledger.files.filter(file => file.path !== 'main.bean'),
      { path: 'main.bean', content: mainBean },
    ].map(file => [file.path, file.content]),
  );
}
