/**
 * SBV ISO 20022 Gateway — Audit Logger
 * Ghi nhật ký kiểm toán cho mọi message ISO 20022 xử lý qua gateway.
 * Đáp ứng yêu cầu AML/CFT của NHNN và FATF Recommendation 16 (Wire Transfer).
 *
 * Log format: JSON structured (Winston) — sẵn sàng ship tới ELK / Splunk
 * Cơ quan chủ quản: Ngân hàng Nhà nước Việt Nam (SBV)
 */

import winston from 'winston';
import { createHash } from 'crypto';

// ─── Logger instance ─────────────────────────────────────────────────────────

const logFormat = winston.format.combine(
  winston.format.timestamp({ format: 'YYYY-MM-DDTHH:mm:ss.SSSZ' }),
  winston.format.json(),
);

const logger = winston.createLogger({
  level:       'info',
  defaultMeta: { service: 'sbv-iso20022-gateway', component: 'audit' },
  transports:  [
    new winston.transports.Console({ format: logFormat }),
    new winston.transports.File({
      filename: 'gateway.log',
      format:   logFormat,
      maxsize:  50 * 1024 * 1024,   // 50 MB rotate
      maxFiles: 10,
    }),
  ],
});

// ─── Types ───────────────────────────────────────────────────────────────────

export interface AuditEntry {
  /** ISO 20022 Message Definition Identifier (vd: pacs.008.001.09) */
  msgDefId:    string;
  /** Unique End-to-end Transaction Reference (UUID v4) */
  uetr?:       string | null;
  /** BIC của tổ chức gửi message */
  senderBic?:  string;
  /** SHA-256 hash toàn bộ message body — dùng để neo trên Gov-Chain */
  msgHash:     string;
  /** Downstream target (NAPAS_DOMESTIC / ASEAN_MBRIDGE / ...) */
  downstream?: string;
  /** Cảnh báo AML/business rule (không block) */
  warnings?:   { field: string; message: string }[];
  /** Trường dữ liệu bổ sung tuỳ ngữ cảnh */
  extra?:      Record<string, unknown>;
}

// ─── Public API ───────────────────────────────────────────────────────────────

/**
 * Ghi audit entry cho một message đã được gateway xử lý thành công.
 * @param entry - Thông tin kiểm toán đầy đủ
 */
export function logAuditEntry(entry: AuditEntry): void {
  const record = {
    event:    'MESSAGE_ACCEPTED',
    ...entry,
    // Đảm bảo không có PII thô trong log (hash thay thế nếu cần)
    timestamp: new Date().toISOString(),
  };
  logger.info(record);

  // AML enhanced due diligence: giao dịch có AML warning → log mức warn riêng
  if (entry.warnings?.some(w => w.message.includes('AML'))) {
    logger.warn({ event: 'AML_ENHANCED_DUE_DILIGENCE', uetr: entry.uetr, msgHash: entry.msgHash });
  }
}

/**
 * Ghi log khi message bị từ chối do validation lỗi.
 */
export function logValidationFailure(
  msgDefId: string,
  senderBic: string | undefined,
  errors: { field: string; message: string }[],
): void {
  logger.warn({
    event:     'MESSAGE_REJECTED',
    msgDefId,
    senderBic,
    errors,
    timestamp: new Date().toISOString(),
  });
}

/**
 * Tính SHA-256 hash của message body (object hoặc XML string).
 * Hàm tiện ích dùng chung giữa router và audit logger.
 */
export function computeMessageHash(body: unknown): string {
  const raw = typeof body === 'string' ? body : JSON.stringify(body);
  return createHash('sha256').update(raw, 'utf8').digest('hex');
}
