import sortBy from "../../sorting/sortBy.js";

/**
 * Utility to get the current call status of a candidate. A single candidate
 * can have multiple call events, though in that case we would expect all but
 * one to be retracted. The most recent non-retracted call is always used to
 * establish a candidate's current call status. The most typical cases will be
 * that a candidate has either:
 *
 * - no calls at all, in which case we return `no-call`; or
 * - a single call with a status of either `winner` or `runoff`, in which case
 *   that call determines the candidate's call status.
 *
 * @param {ContestSummaryResults} contestSummary
 *   The summary-level results of the contest for which we want to get
 *   a candidate's current call status.
 * @param {CandidateId} candidateId
 *   The ID of the candidate.
 * @returns {'winner'|'runoff'|'no-call'}
 */
const getCandidateCallStatus = function getCandidateCallStatus(contestSummary = {}, candidateId) {
  const {
    callsByCandidate = {}
  } = contestSummary;
  const candidateCalls = callsByCandidate[candidateId] || [];
  const sortedCalls = sortBy(candidateCalls, ['timestamp', 'id']);
  return sortedCalls.reduce((status, call) => {
    // ignore retracted calls
    if (call.isRetracted) return status;

    // we don't currently expect a candidate to have multiple unretracted
    // calls, so this means something has gone haywire
    if (status !== 'no-call') {
      // eslint-disable-next-line no-console
      console.warn(`Candidate ${candidateId} has multiple unretracted calls`);
    }
    return call.type;
  }, 'no-call');
};
export default getCandidateCallStatus;