const ChainTransaction = require('../models/ChainTransaction');
const mockChainAdapter = require('./mockChainAdapter');
const persistentStore = require('./persistentStore');

const state = persistentStore.readState();
const transactions = state.transactions;

async function submitTransaction(payload = {}) {
  const transaction = new ChainTransaction({
    sourceService: payload.sourceService,
    actionType: payload.actionType,
    actorId: payload.actorId,
    targetId: payload.targetId,
    amount: payload.amount,
    metadata: payload.metadata
  });

  const chainResult = await mockChainAdapter.submit(transaction.toChainPayload());
  transaction.markConfirmed(chainResult);
  transactions.unshift(transaction);
  persistentStore.writeState(state);

  return transaction;
}

function listTransactions() {
  return transactions;
}

function getTransaction(txId) {
  return transactions.find((transaction) => transaction.id === txId || transaction.txHash === txId);
}

module.exports = {
  submitTransaction,
  listTransactions,
  getTransaction
};
