<?php

namespace CouponsPlus\App\Coupon\Tree\ItemSetsToDiscount;

use WC_Coupon;
use CouponsPlus\App\Coupon\CardData;
use CouponsPlus\App\Offers\BuiltIn\Discount;
use CouponsPlus\Original\Collections\MappedObject;
use CouponsPlus\App\Offers\BuiltIn\FixedPriceInternal;
use CouponsPlus\App\Coupon\Tree\Abilities\ItemSetToDiscountCollectionHandler;
use CouponsPlus\App\Coupon\Tree\Factories\ConditionFilterOrOfferFromDataFactory;

/**
 * Here we might need to potentially register a notification upon completion.
 * So this has the possibility of being changed to a composite handler.
 */
class AvailableItemSetToDiscountCollectionHandler implements ItemSetToDiscountCollectionHandler
{

    protected WC_Coupon $coupon;

    public function __construct(WC_Coupon $coupon/*, here probably the offer id*/)
    {
        $this->coupon = $coupon;
    }

    public function handle(ItemsSetToDiscountCollection $itemsSetsToDiscount)
    {
        $itemsSetsToDiscount->getSetsThatCanBeAppliedPartiallyOrFully()->forEvery(function(ItemsSetToDiscount $itemsSetToDiscount) : void {
            $this->registerDiscounts($itemsSetToDiscount);
        });
    }

    /**
     * This is a blatant duplicate (i mean a literal 1:1 copy) of the one in BuyXGetX (need to refactor it).
     */
    private function registerDiscounts(ItemsSetToDiscount $itemsSetToDiscount)
    {
        /**
         *We should probably add another class (item set to discount dixount registrar)) but rn i am burned out so this will
         * have to do.
         */
        $offerFactory = new ConditionFilterOrOfferFromDataFactory($this->coupon);

        $discountOptions = $itemsSetToDiscount->productToDiscount->getDiscountOptions();

        if ($discountOptions->discountType->is('fixed-price')) {
            $offerData = new CardData(
                FixedPriceInternal::TYPE,
                new MappedObject([
                    'amount' => $discountOptions->discountAmount,
                ])
            );
        } else {
            // todo: let's refactor the FREE logic to the discount offer so that it is a native option of discount
            $isFree = $discountOptions->discountType->is('free');

            $offerData = new CardData(
                Discount::TYPE,
                new MappedObject([
                        'type' => $isFree ? 'percentage' : $discountOptions->discountType->get(),
                        'amount' => $isFree ? 100 : $discountOptions->discountAmount,
                        'scope' => 'filtereditems',
                    ]
                )
            );
        }
        $discount = $offerFactory->create(
            'offer',
            $offerData
        );

        $discount->apply($itemsSetToDiscount->itemsSet);
    }
}