/**
 * VNLH-VND SDK — Institutional Governance Policy Framework
 * Khung chính sách thể chế — liên kết quy định pháp lý với chức năng kỹ thuật.
 *
 * Phân tầng trách nhiệm:
 * ┌──────────────────┬────────────────────────────────────────────────────────┐
 * │ Lập pháp         │ Quốc hội: Luật NHNN 2010, Luật PCRT 2022, Luật GDĐT  │
 * │                  │ 2023 → định nghĩa khung pháp lý ISO 20022             │
 * ├──────────────────┼────────────────────────────────────────────────────────┤
 * │ Hành pháp        │ NHNN: vận hành VNLH-GW, cấp phép, giám sát NHTM      │
 * │                  │ Bộ TC: giám sát ngân sách qua VNLH-GOV channel        │
 * │                  │ Kho bạc: quyết toán NSNN, giao dịch pacs.009 ưu tiên │
 * ├──────────────────┼────────────────────────────────────────────────────────┤
 * │ Tư pháp          │ Tòa án: dùng Gov-Chain blockHash làm chứng cứ điện tử │
 * │                  │ Viện KS: theo dõi giao dịch đánh dấu HOLD/CRITICAL    │
 * ├──────────────────┼────────────────────────────────────────────────────────┤
 * │ Kiểm toán        │ KTNN: kiểm tra audit log immutable trên Gov-Chain      │
 * │                  │ NHNN Thanh tra: báo cáo auth.001/002/018 tự động       │
 * ├──────────────────┼────────────────────────────────────────────────────────┤
 * │ Địa phương       │ UBND tỉnh/TP: ngân sách địa phương qua VNLH-GOV       │
 * │                  │ Sở TC: nhận camt.053/054 statement tự động             │
 * └──────────────────┴────────────────────────────────────────────────────────┘
 */

import type { GovernancePolicy } from './types';
import { AML_THRESHOLD } from './constants';

// ─── Danh mục chính sách ──────────────────────────────────────────────────────

export const GOVERNANCE_POLICIES: GovernancePolicy[] = [

  // ── Lập pháp ────────────────────────────────────────────────────────────────

  {
    name:             'ISO20022_MANDATORY_FIELD_VALIDATION',
    owner:            'LEGISLATIVE',
    applicableToMsgs: ['pacs.*', 'pain.*', 'camt.*', 'auth.*', 'head.*'],
    requiresAnchor:   false,
    requiresEDD:      false,
    legalRef:         'Thông tư XX/2024/TT-NHNN — Áp dụng chuẩn ISO 20022 bắt buộc từ 01/01/2026',
  },
  {
    name:             'FATF_R16_WIRE_TRANSFER',
    owner:            'LEGISLATIVE',
    applicableToMsgs: ['pacs.008.*', 'pacs.009.*', 'pain.001.*'],
    thresholdVnd:     0,   // Áp dụng với MỌI giao dịch chuyển tiền điện tử
    requiresAnchor:   false,
    requiresEDD:      false,
    legalRef:         'FATF Recommendation 16 — Wire Transfer Rule',
  },

  // ── Hành pháp ───────────────────────────────────────────────────────────────

  {
    name:             'SBV_RTGS_LARGE_VALUE',
    owner:            'EXECUTIVE',
    applicableToMsgs: ['pacs.008.*', 'pacs.009.*'],
    thresholdVnd:     AML_THRESHOLD.WIRE_EDD_VND,   // 500 triệu VND
    requiresAnchor:   true,
    requiresEDD:      true,
    legalRef:         'Thông tư 37/2016/TT-NHNN — Quy định RTGS',
  },
  {
    name:             'FX_CONTROL_DECREE70',
    owner:            'EXECUTIVE',
    applicableToMsgs: ['pacs.008.*', 'pacs.009.*'],
    thresholdVnd:     0,
    requiresAnchor:   false,
    requiresEDD:      false,
    legalRef:         'Nghị định 70/2014/NĐ-CP — Quy định về quản lý ngoại hối',
  },
  {
    name:             'CBDC_PILOT_KYC',
    owner:            'EXECUTIVE',
    applicableToMsgs: ['pacs.008.*', 'pain.001.*'],
    requiresAnchor:   true,
    requiresEDD:      true,
    legalRef:         'Quyết định 942/QĐ-TTg 2021 — Chiến lược chuyển đổi số ngành ngân hàng',
  },

  // ── Tư pháp ─────────────────────────────────────────────────────────────────

  {
    name:             'NON_REPUDIATION_EVIDENCE',
    owner:            'JUDICIAL',
    applicableToMsgs: ['pacs.*', 'pain.*'],
    thresholdVnd:     AML_THRESHOLD.GOV_CHAIN_ANCHOR_VND,  // 100 triệu VND
    requiresAnchor:   true,
    requiresEDD:      false,
    legalRef:         'Điều 20 Luật GDĐT 2023 — Tính toàn vẹn và bằng chứng điện tử',
  },
  {
    name:             'DISPUTE_RESOLUTION_CAMT',
    owner:            'JUDICIAL',
    applicableToMsgs: ['camt.055.*', 'camt.056.*'],
    requiresAnchor:   true,
    requiresEDD:      false,
    legalRef:         'ISO 20022 camt.055/056 — Payment Cancellation Request',
  },

  // ── Kiểm toán ───────────────────────────────────────────────────────────────

  {
    name:             'AUDIT_TRAIL_IMMUTABLE',
    owner:            'AUDIT',
    applicableToMsgs: ['pacs.*', 'pain.*', 'camt.*', 'auth.*'],
    requiresAnchor:   true,
    requiresEDD:      false,
    legalRef:         'Điều 55 Luật KTNN 2015 — Lưu trữ tài liệu kiểm toán 10 năm',
  },
  {
    name:             'AML_CFT_REGULATORY_REPORT',
    owner:            'AUDIT',
    applicableToMsgs: ['auth.001.*', 'auth.002.*', 'auth.018.*'],
    requiresAnchor:   true,
    requiresEDD:      true,
    legalRef:         'Luật Phòng, chống rửa tiền 2022 — Báo cáo giao dịch đáng ngờ',
  },
  {
    name:             'SUSPICIOUS_TRANSACTION_REPORT',
    owner:            'AUDIT',
    applicableToMsgs: ['auth.*'],
    thresholdVnd:     AML_THRESHOLD.CASH_REPORT_VND,  // 200 triệu VND
    requiresAnchor:   true,
    requiresEDD:      true,
    legalRef:         'Nghị định 19/2023/NĐ-CP — Hướng dẫn Luật PCRT 2022',
  },

  // ── Địa phương ───────────────────────────────────────────────────────────────

  {
    name:             'LOCAL_GOV_BUDGET_SETTLEMENT',
    owner:            'LOCAL_GOV',
    applicableToMsgs: ['pacs.009.*', 'camt.053.*'],
    requiresAnchor:   true,
    requiresEDD:      false,
    legalRef:         'Luật NSNN 2015 — Thanh toán ngân sách địa phương qua KBNN',
  },
  {
    name:             'LOCAL_GOV_STATEMENT_DELIVERY',
    owner:            'LOCAL_GOV',
    applicableToMsgs: ['camt.053.*', 'camt.054.*'],
    requiresAnchor:   false,
    requiresEDD:      false,
    legalRef:         'Thông tư 77/2017/TT-BTC — Chế độ kế toán NSNN',
  },
];

// ─── Policy Engine ────────────────────────────────────────────────────────────

/**
 * Trả về danh sách chính sách áp dụng cho một message và giá trị giao dịch.
 */
export function getApplicablePolicies(
  msgDefId: string,
  amountVnd: number,
): GovernancePolicy[] {
  return GOVERNANCE_POLICIES.filter(p => {
    const msgMatch = p.applicableToMsgs.some(pattern => {
      const re = new RegExp('^' + pattern.replace(/\./g, '\\.').replace(/\*/g, '.*') + '$');
      return re.test(msgDefId);
    });
    if (!msgMatch) return false;
    if (p.thresholdVnd !== undefined && amountVnd < p.thresholdVnd) return false;
    return true;
  });
}

/**
 * Kiểm tra xem một giao dịch có bắt buộc Gov-Chain anchor theo ít nhất một chính sách không.
 */
export function isPolicyAnchorRequired(msgDefId: string, amountVnd: number): boolean {
  return getApplicablePolicies(msgDefId, amountVnd).some(p => p.requiresAnchor);
}

/**
 * Kiểm tra EDD có bắt buộc không.
 */
export function isPolicyEddRequired(msgDefId: string, amountVnd: number): boolean {
  return getApplicablePolicies(msgDefId, amountVnd).some(p => p.requiresEDD);
}

/**
 * Lấy tất cả văn bản pháp lý tham chiếu áp dụng.
 */
export function getLegalRefs(msgDefId: string, amountVnd: number): string[] {
  return getApplicablePolicies(msgDefId, amountVnd)
    .map(p => p.legalRef)
    .filter((r): r is string => Boolean(r));
}
