<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);

namespace Magento\SalesRule\Model;

use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\SalesRule\Api\CouponRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;

/**
 * @magentoDbIsolation enabled
 * @magentoAppIsolation enabled
 */
class CouponTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @var CouponRepositoryInterface
     */
    private $couponRepository;

    /**
     * @var RuleFactory
     */
    private $ruleFactory;

    public function setUp(): void
    {
        parent::setUp();
        /** @var CouponRepositoryInterface couponRepository */
        $this->couponRepository = Bootstrap::getObjectManager()->create(CouponRepositoryInterface::class);
        /** @var RuleFactory ruleFactory */
        $this->ruleFactory = Bootstrap::getObjectManager()->create(RuleFactory::class);
    }

    /**
     * Check that non-autogenerated coupon contains necessary fields received from sales rule
     */
    public function testNonAutogeneratedCouponBelongingToRule()
    {
        $couponCode = '_coupon__code_';
        $rule = $this->ruleFactory->create();
        $rule->setCouponType(2)
        ->setUseAutoGeneration(0)
        ->setCouponCode($couponCode)
        ->setUsesPerCustomer(null)
        ->setUsesPerCoupon(null)
        ->save();

        /** @var SearchCriteriaBuilder $criteriaBuilder */
        $criteriaBuilder = Bootstrap::getObjectManager()->create(SearchCriteriaBuilder::class);
        $couponSearchResult = $this->couponRepository->getList(
            $criteriaBuilder->addFilter('code', $couponCode, 'like')->create()
        );
        $coupons = $couponSearchResult->getItems();
        $coupon = array_pop($coupons);

        $this->assertEquals(0, $coupon->getUsagePerCustomer());
        $this->assertEquals(0, $coupon->getUsageLimit());
        $this->assertEquals(0, $coupon->getTimesUsed());
        $this->assertEquals(0, $coupon->getType());
        $this->assertNotEmpty($coupon->getCreatedAt());
    }
}
