/**
 * SBV ISO 20022 Gateway — VNLH Gov-Chain Anchor
 * Neo (anchor) hash giao dịch lên SBV Gov-Chain (VNLH-VND layer).
 *
 * Kiến trúc tham chiếu (section 3 & §5 Non-repudiation):
 *   SHA-256(message body) → Gov-Chain transaction → blockHash
 *
 * Trong giai đoạn M1-M2 (triển khai nội địa), anchor được ghi vào
 * audit log cục bộ. Giai đoạn M3 sẽ tích hợp Gov-Chain RPC thật.
 *
 * Cơ quan chủ quản: Ngân hàng Nhà nước Việt Nam (SBV)
 */

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

export interface AnchorResult {
  /** SHA-256 hash của message body đã neo */
  msgHash:    string;
  /** UETR tham chiếu giao dịch */
  uetr?:      string | null;
  /** Trạng thái: pending = chờ Gov-Chain confirm; anchored = đã xác nhận */
  status:     'pending' | 'anchored' | 'failed';
  /** Block hash trả về từ Gov-Chain (null khi chưa confirm) */
  blockHash:  string | null;
  /** Unix timestamp khi anchor được gửi */
  anchoredAt: number;
  /** Lỗi nếu có */
  error?:     string;
}

// ─── Gov-Chain RPC config (placeholder cho M3+) ──────────────────────────────

const GOV_CHAIN_RPC = process.env.GOV_CHAIN_RPC ?? 'http://gov-chain.sbv.gov.vn:8545';
const GOV_CHAIN_ENABLED = process.env.GOV_CHAIN_ENABLED === 'true';

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

/**
 * Neo hash giao dịch lên SBV Gov-Chain.
 *
 * - Giai đoạn M1-M2: lưu trạng thái pending + log local (Gov-Chain chưa live)
 * - Giai đoạn M3+:   gọi Gov-Chain RPC thật, trả về blockHash
 *
 * Hàm này là **fire-and-forget async** — router không block chờ Gov-Chain.
 *
 * @param msgHash  - SHA-256 hash message body (64 hex chars)
 * @param uetr     - UETR của giao dịch
 * @param msgDefId - Message type (pacs.008.001.09, ...)
 */
export async function anchorToGovChain(
  msgHash:  string,
  uetr:     string | null | undefined,
  msgDefId: string,
): Promise<AnchorResult> {
  const anchoredAt = Date.now();

  if (!GOV_CHAIN_ENABLED) {
    // M1-M2 mode: log anchor intent, trả về pending
    console.log(JSON.stringify({
      event:      'GOV_CHAIN_ANCHOR_QUEUED',
      msgHash,
      uetr,
      msgDefId,
      anchoredAt: new Date(anchoredAt).toISOString(),
      note:       `GOV_CHAIN_ENABLED=false — anchor queued for M3 deployment. RPC: ${GOV_CHAIN_RPC}`,
    }));

    return {
      msgHash,
      uetr,
      status:     'pending',
      blockHash:  null,
      anchoredAt,
    };
  }

  // M3+ mode: gọi Gov-Chain RPC thật
  try {
    const payload = {
      method:  'sbv_anchor',
      params:  [{ hash: msgHash, uetr, msgDefId, ts: anchoredAt }],
      id:      1,
      jsonrpc: '2.0',
    };

    const resp = await fetch(GOV_CHAIN_RPC, {
      method:  'POST',
      headers: { 'Content-Type': 'application/json' },
      body:    JSON.stringify(payload),
      signal:  AbortSignal.timeout(5000),   // 5s timeout
    });

    if (!resp.ok) throw new Error(`Gov-Chain HTTP ${resp.status}`);

    const data = (await resp.json()) as { result?: { blockHash: string }; error?: { message: string } };
    if (data.error) throw new Error(data.error.message);

    const blockHash = data.result?.blockHash ?? null;
    console.log(JSON.stringify({ event: 'GOV_CHAIN_ANCHORED', msgHash, uetr, blockHash }));

    return { msgHash, uetr, status: 'anchored', blockHash, anchoredAt };

  } catch (err) {
    const error = (err as Error).message;
    console.error(JSON.stringify({ event: 'GOV_CHAIN_ANCHOR_FAILED', msgHash, uetr, error }));
    return { msgHash, uetr, status: 'failed', blockHash: null, anchoredAt, error };
  }
}
