import { redact } from './log-redactor';

interface AuditLogOptions {
  userId: number;
  action: 'CREATE' | 'UPDATE' | 'DELETE' | 'APPROVE' | 'REJECT' | 'LOGIN';
  targetTable: string;
  targetId: number;
  previousValue?: any;
  newValue?: any;
  ipAddress?: string | null;
}

/**
 * Creates a redacted audit log entry.
 * Strips password hashes and personal financial metrics from values.
 */
export async function createAuditLog(tx: any, options: AuditLogOptions) {
  const redactedPrev = options.previousValue ? redact(JSON.parse(JSON.stringify(options.previousValue))) : null;
  const redactedNew = options.newValue ? redact(JSON.parse(JSON.stringify(options.newValue))) : null;
  
  return await tx.auditLog.create({
    data: {
      userId: options.userId,
      action: options.action,
      targetTable: options.targetTable,
      targetId: options.targetId,
      previousValue: redactedPrev,
      newValue: redactedNew,
      ipAddress: options.ipAddress || null,
    }
  });
}
