const KnightRule = require("./rules/knightrule");
const ElfBowRule = require("./rules/elfbowrule");
const ElfArrowRule = require("./rules/elfarrowrule");
const MinerRule = require("./rules/minerrule");

const sale = {
  sellItems: function(customer, items) {
    const sum = (current, previous) => current + previous;
    const total =
      items
      .map(item => item.price)
      .reduce(sum, 0);

    return {customer, items, total, date: new Date()};
  },
  applyDiscount: function(customer, items) {
    const rules = [new KnightRule, new ElfBowRule, new ElfArrowRule, new MinerRule];
    rules.filter(rule => rule
      .appliable(customer, items))
      .forEach(rule => items = rule.apply(items));

    const result =
      items
      .map(item => {
        return {
          price: item.price,
          name: item.name,
          type: item.type,
          finalPrice: item.finalPrice === undefined ? item.price: item.finalPrice
        }
      }
    );

    return result;
  }
};

module.exports = sale;
