<?php


namespace Shop\Repositories\Discount;


use Diamond\Repositories\PropelAbstractRepository;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Repo\CollectionInterface;
use Repo\CrudRepositoryBuilderInterface;
use Repo\EntityInterface;
use Repo\PaginationInterface;
use Shop\Domain\Discount\Contracts\DiscountEntityInterface;
use Shop\Domain\Discount\DiscountCollection;
use Shop\Models\Discount\Discount;
use Shop\Models\Discount\DiscountQuery;

class DiscountRepository extends PropelAbstractRepository implements CrudRepositoryBuilderInterface
{
    /**
     * @return EntityInterface
     */
    public static function createEntity(): EntityInterface
    {
        return new Discount();
    }

    /**
     * @return ModelCriteria
     */
    protected function createQuery(): ModelCriteria
    {
        return DiscountQuery::create();
    }

    /**
     * @param PaginationInterface $criteria
     * @param ModelCriteria $dbCriteria
     */
    protected function modifyCriteria(PaginationInterface $criteria, ModelCriteria $dbCriteria): void
    {
        $this->modifyCriteriaForFilterSort($criteria, $dbCriteria);
    }

    /**
     * @param PaginationInterface $criteria
     * @return CollectionInterface
     * @throws \Repo\Concrete\Exceptions\Collection
     */
    public function findByCriteria(PaginationInterface $criteria): CollectionInterface
    {
        $query = $this->createQuery();
        $this->modifyCriteria($criteria, $query);
        $result = $query->paginate($criteria->getPage(), $criteria->getLimit());

        $collection = new DiscountCollection();

        foreach ($result->getResults() as $row) {
            $collection->push($row);
        }

        return $collection;
    }


    /**
     * @param float $sum
     * @return DiscountEntityInterface|null
     */
    public function findNextDiscount(float $sum): ?DiscountEntityInterface
    {
        return $this
            ->createQuery()
            ->filterByPriceFrom($sum, Criteria::GREATER_THAN)
            ->orderByPriceFrom(Criteria::ASC)
            ->orderByPercent(Criteria::DESC)
            ->findOne();
    }

    /**
     * получение скидки которая входит в диапазон
     * @param float $sum
     * @return DiscountEntityInterface|null
     */
    public function findDiscount(float $sum): ?DiscountEntityInterface
    {
        return $this
            ->createQuery()
            ->filterByPriceFrom($sum, Criteria::LESS_EQUAL)
            ->filterByPriceTo($sum, Criteria::GREATER_THAN)
            ->orderByPercent(Criteria::DESC)
            ->findOne();
    }
}