<?php

namespace CouponsPlus\App\Coupon\Tree\Offeritemssetfilters;

use CouponsPlus\App\Conditions\ItemsSet;
use CouponsPlus\App\Coupon\Tree\Abilities\WithIdentifier;
use CouponsPlus\App\Coupon\Tree\Offeritemssetfilters\Abilities\FilterableOfferItems;
use CouponsPlus\App\Offers\BuiltIn\Discount;
use CouponsPlus\Original\Characters\StringManager;
use CouponsPlus\Original\Collections\MappedObject;

class DiscountItemsFilter implements WithIdentifier, FilterableOfferItems
{
    public function getIdentifier(): StringManager
    {
        return new StringManager(Discount::TYPE);
    } 

    public function filterSet(MappedObject $options, ItemsSet $itemsSet): ItemsSet
    {
        // if it's 'apply to cart subtotal', get all of them items
        if ($options->scope->is('cartsubtotal')) {
            // we'very important: we're passing all the items since the scoe is cart subtotal
            // however, we don't want them to be excluded in the next tree when calling ItemsSet::without()
            $itemsSet->excludeItems(false);

            return $itemsSet;
        }

        if (!$options->limit->isEnabled) {
            return $itemsSet;
        }

        // if has a limit, get that limit and order it by cheapest first!        
        return new ItemsSet(
            $itemsSet->getAMaximumOf(max($options->limit->amount, 1))->getSortedItems()
        );
    } 
}