import { readFileSync, existsSync } from 'fs';
import { resolve } from 'path';

export interface JournalMatrixEntry {
  memo: string;
  officeId: number;
  debitGlCode: string;
  creditGlCode: string;
  amount: number;
  narrative: string;
  ipsasRef: string;
}

export interface JournalMatrixFile {
  entries: JournalMatrixEntry[];
  description?: string;
  source?: string;
  currencyCode?: string;
}

export function loadJournalMatrixPath(): string {
  return (
    process.env.OMNL_JOURNAL_MATRIX_PATH ||
    resolve(__dirname, '../../../../config/omnl-journal-matrix.json')
  );
}

export function loadJournalMatrix(): JournalMatrixFile {
  const p = loadJournalMatrixPath();
  if (!existsSync(p)) {
    throw new Error(`Journal matrix not found: ${p}. Set OMNL_JOURNAL_MATRIX_PATH.`);
  }
  return JSON.parse(readFileSync(p, 'utf8')) as JournalMatrixFile;
}

/** Union of IPSAS registry pairs and matrix-derived pairs for validation. */
export function matrixPairSet(matrix: JournalMatrixFile): Set<string> {
  const s = new Set<string>();
  for (const e of matrix.entries) {
    s.add(`${e.debitGlCode}|${e.creditGlCode}`);
  }
  return s;
}
