<?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('CAST(`shop_discounts`.`price_from` AS DECIMAL) > CAST(' . $sum . ' AS DECIMAL)',
                Criteria::CUSTOM)
            ->orderByPriceFrom(Criteria::ASC)
            ->orderByPercent(Criteria::DESC)
            ->findOne();
    }

    /**
     * получение скидки которая входит в диапазон
     * @param float $sum
     * @return DiscountEntityInterface|null
     */
    public function findDiscount(float $sum): ?DiscountEntityInterface
    {
        return $this
            ->createQuery()
            ->filterByPriceFrom('CAST(`shop_discounts`.`price_from` AS DECIMAL) <= CAST(' . $sum . ' AS DECIMAL)',
                Criteria::CUSTOM)
            ->filterByPriceTo('CAST(`shop_discounts`.`price_to` AS DECIMAL) > CAST(' . $sum . ' AS DECIMAL)',
                Criteria::CUSTOM)
            ->orderByPercent(Criteria::DESC)
            ->findOne();
    }
}