<?php

namespace Shop\Infrastructure\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\Infrastructure\Models\Discount\Discount;
use Shop\Infrastructure\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
    {
 
    }



    protected function createCollection(): CollectionInterface
    {
        return new DiscountCollection();
    }

    /**
     * @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();
    }
}