const express = require('express');
const canonicalLedgerService = require('../services/canonicalLedgerService');

const router = express.Router();

router.get('/status', async (req, res, next) => {
  try {
    const canonical = await canonicalLedgerService.refreshStatus();
    res.status(canonical.online ? 200 : 503).json({ ok: canonical.online, canonical });
  } catch (error) {
    next(error);
  }
});

router.get('/block/:blockId', async (req, res, next) => {
  try {
    const block = await canonicalLedgerService.getBlock(req.params.blockId);
    if (!block) return res.status(404).json({ ok: false, error: 'CANONICAL_BLOCK_NOT_FOUND' });
    return res.json({ ok: true, ledgerRole: 'canonical-candidate-ledger', block });
  } catch (error) {
    return next(error);
  }
});

router.get('/tx/:txHash', async (req, res, next) => {
  try {
    const transaction = await canonicalLedgerService.getTransaction(req.params.txHash);
    if (!transaction) return res.status(404).json({ ok: false, error: 'CANONICAL_TRANSACTION_NOT_FOUND' });
    return res.json({ ok: true, ledgerRole: 'canonical-candidate-ledger', transaction });
  } catch (error) {
    return next(error);
  }
});

module.exports = router;
