const PointLedger = require('../models/PointLedger');
const persistentStore = require('./persistentStore');
const { getProofRewardPoints } = require('../contracts/proofContract');

const state = persistentStore.readState();
const entries = state.pointEntries;

function createEntry(payload = {}) {
  const entry = new PointLedger(payload);
  entries.unshift(entry);
  persistentStore.writeState(state);
  return entry;
}

function rewardProof(proof, chainRef = {}) {
  const points = getProofRewardPoints(proof.proofType);

  if (points <= 0) {
    return null;
  }

  return createEntry({
    actorId: proof.actorId,
    sourceService: proof.sourceService,
    reason: `PROOF_${proof.proofType}`,
    points,
    refType: 'proof',
    refId: proof.id,
    metadata: chainRef
  });
}

function listEntries() {
  return entries;
}

module.exports = {
  createEntry,
  rewardProof,
  listEntries
};
