import { appendFileSync, mkdirSync } from 'fs';
import { dirname, resolve } from 'path';
import { randomUUID } from 'crypto';

export type OmnlAuditEntry = {
  id: string;
  ts: string;
  category: 'api' | 'fineract' | 'webhook_out' | 'webhook_in' | 'reconcile' | 'iso20022';
  action: string;
  actor?: string;
  sourceSystem?: string;
  traceId?: string;
  referenceNumber?: string;
  transactionHash?: string;
  journalEntryId?: string;
  status?: 'ok' | 'error' | 'skipped';
  metadata?: Record<string, unknown>;
};

export function omnlAuditLogPath(): string {
  const raw = process.env.OMNL_AUDIT_LOG_PATH?.trim();
  if (raw) return resolve(raw);
  const root = process.env.PROXMOX_ROOT || process.env.PHOENIX_REPO_ROOT || process.cwd();
  return resolve(root, 'reports/audit/omnl-audit.jsonl');
}

/** Append-only JSONL audit trail (immutable by convention — no delete API). */
export function appendOmnlAudit(entry: Omit<OmnlAuditEntry, 'id' | 'ts'> & { id?: string; ts?: string }): void {
  const path = omnlAuditLogPath();
  mkdirSync(dirname(path), { recursive: true });
  const row: OmnlAuditEntry = {
    id: entry.id || randomUUID(),
    ts: entry.ts || new Date().toISOString(),
    ...entry,
  };
  appendFileSync(path, `${JSON.stringify(row)}\n`, 'utf8');
}
