/**
 * VNLH-VND SDK — Extended Router
 * Các endpoint bổ sung dành riêng cho hạ tầng VNLH-VND:
 *
 *   POST /api/v1/iso20022/vnlh/screen        - AML/CFT screening độc lập
 *   POST /api/v1/iso20022/vnlh/netting       - EOD VND netting calculation
 *   POST /api/v1/iso20022/vnlh/fx-check      - Kiểm tra kiểm soát ngoại hối
 *   GET  /api/v1/iso20022/vnlh/chain/:hash   - Tra cứu Gov-Chain anchor
 *   GET  /api/v1/iso20022/vnlh/policies      - Danh sách chính sách thể chế
 *   GET  /api/v1/iso20022/vnlh/token         - Lấy SWIFT OAuth2 token (admin)
 *   GET  /api/v1/iso20022/vnlh/sdk-info      - Thông tin phiên bản SDK
 *
 * Cơ quan chủ quản: Ngân hàng Nhà nước Việt Nam (SBV)
 */

import express, { Request, Response } from 'express';
import {
  VnlhSdk,
  routeAndScreen,
  computeVndNetting,
  checkFxControl,
  queryGovChain,
  getApplicablePolicies,
  getLegalRefs,
  getSwiftSession,
  processKycSubmit,
  scanOdcDocument,
} from '../vnlh';
import type { ControlledCurrency, NettingInput, KycSubmitInput, OdcDocType } from '../vnlh';

export const vnlhRouter = express.Router();

// ─── POST /vnlh/screen ───────────────────────────────────────────────────────

/**
 * AML/CFT Screening độc lập cho một giao dịch trước khi submit.
 * Cho phép NHTM kiểm tra trước rủi ro mà không cần gửi message thật.
 *
 * Body: { msgDefId, amountVnd, currency, senderBic, uetr, crossBorder? }
 */
vnlhRouter.post('/screen', express.json(), async (req: Request, res: Response) => {
  const { msgDefId, amountVnd, currency, senderBic, uetr, crossBorder } = req.body;

  const missing = ['msgDefId', 'amountVnd', 'currency', 'senderBic', 'uetr']
    .filter(k => req.body[k] === undefined || req.body[k] === null || req.body[k] === '');

  if (missing.length > 0) {
    return res.status(400).json({ code: 'MISSING_FIELDS', fields: missing });
  }
  if (typeof amountVnd !== 'number' || amountVnd <= 0) {
    return res.status(400).json({ code: 'INVALID_AMOUNT', message: 'amountVnd phải là số dương (VND)' });
  }

  const decision  = routeAndScreen({ msgDefId, amountVnd, currency, senderBic, uetr, crossBorder });
  const legalRefs = getLegalRefs(msgDefId, amountVnd);
  const policies  = getApplicablePolicies(msgDefId, amountVnd).map(p => ({
    name:  p.name,
    owner: p.owner,
    legalRef: p.legalRef,
  }));

  return res.status(200).json({
    code:            'SCREENED',
    decision:        {
      downstream:      decision.downstream,
      requiresRTGS:    decision.requiresRTGS,
      requiresEDD:     decision.requiresEDD,
      requiresAnchor:  decision.requiresAnchor,
    },
    aml:             decision.amlResult,
    applicablePolicies: policies,
    legalRefs,
    screenedAt:      new Date().toISOString(),
  });
});

// ─── POST /vnlh/netting ──────────────────────────────────────────────────────

/**
 * Tính vị thế ròng VND EOD từ danh sách giao dịch ngày.
 * Dùng bởi NHNN / NAPAS để quyết toán cuối ngày.
 *
 * Body: { valueDt, transactions: NettingInput[] }
 */
vnlhRouter.post('/netting', express.json(), async (req: Request, res: Response) => {
  const { valueDt, transactions } = req.body;

  if (!valueDt || !Array.isArray(transactions) || transactions.length === 0) {
    return res.status(400).json({
      code: 'INVALID_INPUT',
      message: 'Yêu cầu valueDt (YYYY-MM-DD) và mảng transactions không rỗng',
    });
  }

  const positions = computeVndNetting(
    (transactions as NettingInput[]).map(t => ({ ...t, valueDt }))
  );

  return res.status(200).json({
    code:       'NETTING_COMPUTED',
    valueDt,
    positions,
    totalDebit:  positions.filter(p => p.netAmount < 0).reduce((s, p) => s + Math.abs(p.netAmount), 0),
    totalCredit: positions.filter(p => p.netAmount > 0).reduce((s, p) => s + p.netAmount, 0),
    computedAt:  new Date().toISOString(),
  });
});

// ─── POST /vnlh/fx-check ─────────────────────────────────────────────────────

/**
 * Kiểm tra giao dịch ngoại tệ theo Nghị định 70/2014.
 * Body: { amountUsd, currency, senderType, crossBorder }
 */
vnlhRouter.post('/fx-check', express.json(), async (req: Request, res: Response) => {
  const { amountUsd, currency, senderType, crossBorder } = req.body;

  if (!amountUsd || !currency || !senderType) {
    return res.status(400).json({ code: 'MISSING_FIELDS', fields: ['amountUsd', 'currency', 'senderType'] });
  }

  const result = checkFxControl({
    amountUsd:   Number(amountUsd),
    currency:    currency as ControlledCurrency,
    senderType,
    crossBorder: Boolean(crossBorder),
  });

  return res.status(200).json({
    code:   'FX_CHECKED',
    result,
    legalRef: 'Nghị định 70/2014/NĐ-CP — Quản lý ngoại hối',
    checkedAt: new Date().toISOString(),
  });
});

// ─── GET /vnlh/chain/:hash ────────────────────────────────────────────────────

/**
 * Tra cứu trạng thái anchor trên Gov-Chain theo SHA-256 hash.
 * Dùng bởi Tư pháp / KTNN để xác thực tính toàn vẹn giao dịch.
 */
vnlhRouter.get('/chain/:hash', async (req: Request, res: Response) => {
  const { hash } = req.params;
  if (!/^[0-9a-f]{64}$/.test(hash)) {
    return res.status(400).json({ code: 'INVALID_HASH', message: 'Hash phải là SHA-256 hex 64 ký tự' });
  }
  const anchor = await queryGovChain(hash);
  if (!anchor) {
    return res.status(404).json({
      code:    'NOT_FOUND',
      message: 'Hash chưa được neo trên Gov-Chain hoặc Gov-Chain chưa kích hoạt (M3)',
      hash,
    });
  }
  return res.status(200).json({ code: 'FOUND', anchor });
});

// ─── GET /vnlh/policies ───────────────────────────────────────────────────────

/**
 * Trả về toàn bộ danh mục chính sách thể chế của VNLH-VND.
 * Dùng để audit, tra cứu pháp lý, và tài liệu hóa.
 */
vnlhRouter.get('/policies', (_req: Request, res: Response) => {
  const { GOVERNANCE_POLICIES } = require('../vnlh/governance-policy');
  res.status(200).json({
    code:     'OK',
    count:    GOVERNANCE_POLICIES.length,
    policies: GOVERNANCE_POLICIES,
  });
});

// ─── GET /vnlh/token ─────────────────────────────────────────────────────────

/**
 * Lấy SWIFT OAuth2 Access Token (chỉ dành cho admin / internal services).
 * Header: X-VNLH-Admin: <admin_token>
 */
vnlhRouter.get('/token', async (req: Request, res: Response) => {
  const adminToken = req.headers['x-vnlh-admin'];
  if (adminToken !== process.env.VNLH_ADMIN_TOKEN) {
    return res.status(403).json({ code: 'FORBIDDEN', message: 'X-VNLH-Admin token không hợp lệ' });
  }
  try {
    const session = getSwiftSession();
    const token   = await session.getToken();
    // Không trả về access_token thô — chỉ meta
    return res.status(200).json({
      code:       'TOKEN_ISSUED',
      token_type: token.token_type,
      expires_in: token.expires_in,
      scope:      token.scope,
      issuedAt:   new Date(token.issuedAt).toISOString(),
      expiresAt:  new Date(token.expiresAt).toISOString(),
    });
  } catch (err) {
    return res.status(502).json({ code: 'SWIFT_OAUTH_ERROR', message: (err as Error).message });
  }
});

// ─── POST /vnlh/kyc/submit ────────────────────────────────────────────────────
/**
 * Nộp hồ sơ KYC theo ISO 20022 auth.012.
 * Body: KycSubmitInput (JSON)
 * Returns: { kycId, status, riskLevel, auth012Xml, auth013Xml, ... }
 */
vnlhRouter.post('/kyc/submit', express.json(), async (req: Request, res: Response) => {
  const input = req.body as KycSubmitInput;

  if (!input.fullName || !input.idNumber || !input.requesterBic) {
    return res.status(400).json({
      code:    'MISSING_FIELDS',
      message: 'Thiếu trường bắt buộc: fullName, idNumber, requesterBic',
    });
  }

  try {
    const result = processKycSubmit(input);
    return res.status(201).json({ code: 'KYC_SUBMITTED', ...result });
  } catch (err) {
    return res.status(500).json({ code: 'KYC_ERROR', message: (err as Error).message });
  }
});

// ─── POST /vnlh/kyc/scan ──────────────────────────────────────────────────────
/**
 * Quét tài liệu số (ODC scan đơn lẻ).
 * Body: { docType, content, fileName?, mimeType?, fileSize? }
 */
vnlhRouter.post('/kyc/scan', express.json(), async (req: Request, res: Response) => {
  const { docType, content, fileName, mimeType, fileSize } = req.body;

  const supported: OdcDocType[] = [
    'NATIONAL_ID','PASSPORT','DRIVING_LIC','BUSINESS_REG',
    'CONTRACT','LEGAL_DOC','FINANCIAL_STMT','OTHER',
  ];

  if (!docType || !supported.includes(docType as OdcDocType)) {
    return res.status(400).json({
      code:      'INVALID_DOC_TYPE',
      supported,
      message:   `docType '${docType}' không hợp lệ`,
    });
  }

  try {
    const result = scanOdcDocument({ docType: docType as OdcDocType, content: content || '', fileName, mimeType, fileSize });
    return res.status(200).json({ code: 'SCAN_COMPLETE', ...result });
  } catch (err) {
    return res.status(500).json({ code: 'ODC_SCAN_ERROR', message: (err as Error).message });
  }
});

// ─── POST /vnlh/kyc/contract ──────────────────────────────────────────────────
/**
 * Phân tích hợp đồng / văn bản pháp lý.
 * Body: { content, docType?: 'CONTRACT'|'LEGAL_DOC', fileName? }
 */
vnlhRouter.post('/kyc/contract', express.json(), async (req: Request, res: Response) => {
  const { content, docType = 'CONTRACT', fileName } = req.body;

  if (!content) {
    return res.status(400).json({ code: 'MISSING_CONTENT', message: 'content là bắt buộc' });
  }

  try {
    const scanResult = scanOdcDocument({
      docType: docType as OdcDocType,
      content, fileName: fileName || 'contract.pdf',
      mimeType: 'application/pdf',
    });

    return res.status(200).json({
      code:             'CONTRACT_VERIFIED',
      docHash:          scanResult.docHash,
      verifyStatus:     scanResult.verifyStatus,
      ocrFields:        scanResult.ocrFields,
      ocrConfidence:    scanResult.ocrConfidence,
      contractAnalysis: scanResult.contractRisk,
      expiry:           scanResult.expiryDays !== undefined
        ? { daysRemaining: scanResult.expiryDays, valid: (scanResult.expiryDays ?? 1) > 0 }
        : null,
      legalFramework: {
        'Hợp đồng':  'Bộ luật Dân sự 2015 — Điều 385-408',
        'Tín dụng':  'Thông tư 39/2016/TT-NHNN',
        'Điện tử':   'Luật GDĐT 2023',
        'Chứng cứ':  'Điều 20 Luật GDĐT 2023 — Gov-Chain blockHash',
      },
      verifiedAt: new Date().toISOString(),
    });
  } catch (err) {
    return res.status(500).json({ code: 'CONTRACT_ERROR', message: (err as Error).message });
  }
});

// ─── GET /vnlh/kyc/schemas ────────────────────────────────────────────────────
/** Danh sách loại tài liệu ODC hỗ trợ + ISO 20022 reference. */
vnlhRouter.get('/kyc/schemas', (_req: Request, res: Response) => {
  res.status(200).json({
    code: 'OK',
    docTypes: [
      { docType: 'NATIONAL_ID',    label: 'CMND/CCCD — Căn cước công dân',               maxAgeYears: 15 },
      { docType: 'PASSPORT',       label: 'Hộ chiếu Việt Nam',                            maxAgeYears: 10 },
      { docType: 'DRIVING_LIC',    label: 'Giấy phép lái xe',                             maxAgeYears: 10 },
      { docType: 'BUSINESS_REG',   label: 'Giấy đăng ký kinh doanh',                      maxAgeYears: null },
      { docType: 'CONTRACT',       label: 'Hợp đồng tín dụng / Hợp đồng dịch vụ',        maxAgeYears: null },
      { docType: 'LEGAL_DOC',      label: 'Văn bản pháp lý (Nghị quyết, Quyết định...)',  maxAgeYears: null },
      { docType: 'FINANCIAL_STMT', label: 'Báo cáo tài chính',                            maxAgeYears: null },
      { docType: 'OTHER',          label: 'Tài liệu khác',                                maxAgeYears: null },
    ],
    iso20022: {
      kycRequest:  'auth.012.001.02 — MoneyLaunderingRiskReport',
      kycResponse: 'auth.013.001.02 — InvestigationRequestResponse',
    },
    legalRefs: [
      'Thông tư 09/2023/TT-NHNN — eKYC điện tử',
      'Thông tư 16/2021/TT-NHNN — Nhận biết khách hàng điện tử',
      'FATF Recommendation 10 — Customer Due Diligence',
      'FATF Recommendation 12 — Politically Exposed Persons',
    ],
  });
});

// ─── GET /vnlh/sdk-info ───────────────────────────────────────────────────────

vnlhRouter.get('/sdk-info', (_req: Request, res: Response) => {
  res.status(200).json({
    code:    'OK',
    sdk:     VnlhSdk.toString(),
    version: {
      vnlhSdk:     VnlhSdk.version,
      swiftSdk:    VnlhSdk.swiftSdkVersion,
      securitySdk: VnlhSdk.securitySdkVersion,
      iso20022:    VnlhSdk.iso20022Year,
    },
    swiftSdkPath:     '/var/app/docx/SWIFT/swift-sdk-2.17.10-6/bin',
    securitySdkJar:   'swift-security-sdk-2.17.5-6.jar',
    govChainRpc:      process.env.GOV_CHAIN_RPC ?? 'http://gov-chain.sbv.gov.vn:8545',
    govChainEnabled:  process.env.GOV_CHAIN_ENABLED === 'true',
    swiftEnvironment: process.env.SWIFT_ENVIRONMENT ?? 'PILOT',
  });
});
