export default function getContestMargins(type, results) {
  let total;
  let dem;
  let gop;
  let demPct = 0;
  let gopPct = 0;
  let winner;
  if (type === 'historical') {
    total = parseInt(results.total, 10);
    dem = parseInt(results.dem, 10);
    gop = parseInt(results.gop, 10);
    const denominator = total || 1;
    demPct = dem / denominator;
    gopPct = gop / denominator;
  }
  if (type === 'current') {
    const {
      candidateResults,
      candidates,
      contestStatus
    } = results;
    total = Object.entries(candidateResults).reduce((acc, [, current]) => {
      // eslint-disable-next-line no-param-reassign
      acc += current.votes;
      return acc;
    }, 0);
    const demCandidate = candidates.find(c => c.party === 'dem');
    const gopCandidate = candidates.find(c => c.party === 'gop');
    if (demCandidate) {
      dem = candidateResults[demCandidate.id].votes;
      demPct = candidateResults[demCandidate.id].votesPercent;
    }
    if (gopCandidate) {
      gop = candidateResults[gopCandidate.id].votes;
      gopPct = candidateResults[gopCandidate.id].votesPercent;
    }
    winner = contestStatus.winningParty || contestStatus.leadingParty;
  }
  if (!dem && !gop) {
    return undefined;
  }
  return {
    ...results,
    total,
    dem,
    gop,
    demMargin: demPct - gopPct,
    gopMargin: gopPct - demPct,
    party: winner || (dem > gop ? 'dem' : 'gop')
  };
}