const osEl = {
    $discountList: () => $('.checkout-widget__details-discount').find('ul'),
    discountItem: '.checkout-widget__details-discount',
};

export function updateDiscount(data, isVoucher) {
    const promotions = data?.promotionsInfo;

    if (!Array.isArray(promotions) || promotions.length === 0) {
        $(osEl.discountItem).hide();
        return;
    }

    $(osEl.discountItem).show();
    osEl.$discountList().empty();

    if (isVoucher) {
        promotions.forEach((discountItem) => {
            osEl.$discountList().append(() => {
                if (discountItem.usedCouponCode && discountItem.description) {
                    return `
            <li data-coupon-code="${discountItem.usedCouponCode}">
              ${discountItem.description}
              <span class="icon checkout-widget__voucher-remove">
                <span class="fas fa-times"></span>
              </span>
            </li>
          `;
                }

                if (discountItem.description) {
                    return `<li>${discountItem.description}</li>`;
                }

                return '';
            });
        });

        return;
    }

    promotions.forEach((discountObj) => {
        appendOrderPromotions(discountObj);
    });
}

function appendOrderPromotions(discountObj) {
    if (!_.isEmpty(discountObj)) {
        if (discountObj.usedCouponCode && discountObj.description) {
            osEl.$discountList().append(createRemoveCouponItem(discountObj));
        } else if (discountObj.description) {
            osEl.$discountList().append(function () {
                return `<li>${discountObj.description}</li>`;
            });
        }
    }
}

function createRemoveCouponItem(obj) {
    return `
    <li data-coupon-code="${obj.usedCouponCode}">
      ${obj.description}
      <span class="icon checkout-widget__voucher-remove">
        <span class="fas fa-times"></span>
      </span>
    </li>
`;
}
