import { useContestCollectionMetadata } from "../index.js";

/**
 * Reduces a contest collection down to one FIPS code
 * @param {string} collectionId
 * @param {string} moduleName // Optional module name for more detailed console warnings
 * @returns {string} FIPS code
 */

const useContestCollectionStateFips = (collectionId, moduleName = '') => {
  const collectionMetadata = useContestCollectionMetadata(collectionId);
  const contests = Object.values(collectionMetadata || {});
  return contests.reduce((resultFips, currentContest) => {
    const {
      stateFips
    } = currentContest;
    // Guard against mismatched state FIPS code
    if (resultFips && resultFips !== currentContest.stateFips) {
      // eslint-disable-next-line no-console
      console.warn(`${moduleName} Ignoring contest with mismatched state FIPS code` + ` (${currentContest.id} with FIPS ${currentContest.stateFips})`);
      return resultFips;
    }
    return stateFips;
  }, undefined);
};
export default useContestCollectionStateFips;