const { CANONICAL_LEDGER_CONFIG, isCanonicalBesuQbft } = require('../config/canonicalLedgerConfig');
const evmCandidateNetworkService = require('./evmCandidateNetworkService');
const assetPolicyService = require('./assetPolicyService');

let cachedStatus = {
  id: CANONICAL_LEDGER_CONFIG.id,
  role: CANONICAL_LEDGER_CONFIG.role,
  canonical: isCanonicalBesuQbft(),
  online: false,
  checkedAt: null,
  error: 'CANONICAL_STATUS_NOT_CHECKED'
};
let monitor = null;

function decorate(status) {
  return {
    ...status,
    assetPolicy: assetPolicyService.getStatus(),
    id: CANONICAL_LEDGER_CONFIG.id,
    role: CANONICAL_LEDGER_CONFIG.role,
    canonical: isCanonicalBesuQbft(),
    checkedAt: new Date().toISOString()
  };
}

async function refreshStatus() {
  cachedStatus = decorate(await evmCandidateNetworkService.getStatus());
  return cachedStatus;
}

function getStatus() {
  return { ...cachedStatus };
}

function getValidators() {
  return (cachedStatus.validators || []).map((address, index) => ({
    nodeId: address,
    address,
    displayName: `QBFT Validator ${index + 1}`,
    status: cachedStatus.online ? 'online' : 'unknown',
    role: 'qbft-validator',
    canonical: true
  }));
}

function startMonitor(intervalMs = 10000) {
  if (monitor) return monitor;
  refreshStatus().catch(() => {});
  monitor = setInterval(() => {
    refreshStatus().catch(() => {});
  }, Math.max(5000, Number(intervalMs) || 10000));
  monitor.unref();
  return monitor;
}

async function getBlock(blockId) {
  if (!isCanonicalBesuQbft()) return null;
  return evmCandidateNetworkService.getBlock(blockId);
}

async function getTransaction(txHash) {
  if (!isCanonicalBesuQbft()) return null;
  return evmCandidateNetworkService.getTransaction(txHash);
}

module.exports = {
  getBlock,
  getStatus,
  getTransaction,
  getValidators,
  refreshStatus,
  startMonitor
};
