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

const router = express.Router();

router.get('/', (req, res) => {
  res.json({
    ok: true,
    transactions: chainTransactionService.listTransactions()
  });
});

router.get('/:txId', (req, res) => {
  const transaction = chainTransactionService.getTransaction(req.params.txId);

  if (!transaction) {
    return res.status(404).json({
      ok: false,
      error: 'TX_NOT_FOUND'
    });
  }

  return res.json({
    ok: true,
    transaction
  });
});

router.post('/', async (req, res, next) => {
  try {
    const transaction = await chainTransactionService.submitTransaction(req.body);
    res.status(201).json({
      ok: true,
      transaction
    });
  } catch (err) {
    next(err);
  }
});

module.exports = router;
