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

export type OmnlEntitySummary = {
  clientNumber: number;
  accountNo: string;
  entityName: string;
  lei: string;
  source: 'fineract_master_data';
};

function proxmoxRoot(): string {
  return (
    process.env.PROXMOX_ROOT?.trim() ||
    process.env.PHOENIX_REPO_ROOT?.trim() ||
    resolve(process.cwd(), '../../../..')
  );
}

export function listOmnlEntities(): {
  source: string;
  count: number;
  entities: OmnlEntitySummary[];
} {
  const path = resolve(
    proxmoxRoot(),
    'docs/04-configuration/mifos-omnl-central-bank/OMNL_ENTITY_MASTER_DATA.json'
  );
  if (!existsSync(path)) {
    return { source: path, count: 0, entities: [] };
  }
  const raw = JSON.parse(readFileSync(path, 'utf8')) as {
    entities?: Array<{
      clientNumber: number;
      accountNo: string;
      entityName: string;
      lei?: string;
    }>;
  };
  const entities = (raw.entities ?? []).map((e) => ({
    clientNumber: e.clientNumber,
    accountNo: e.accountNo,
    entityName: e.entityName,
    lei: e.lei ?? '',
    source: 'fineract_master_data' as const,
  }));
  return { source: path, count: entities.length, entities };
}

export function getOmnlEntity(clientNumber: number): OmnlEntitySummary | null {
  const { entities } = listOmnlEntities();
  return entities.find((e) => e.clientNumber === clientNumber) ?? null;
}
