<?php

declare(strict_types=1);

namespace Doctrine\Tests\ORM\Functional;

use Doctrine\ORM\PersistentCollection;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\ECommerce\ECommerceCart;
use Doctrine\Tests\Models\ECommerce\ECommerceCustomer;
use Doctrine\Tests\Models\ECommerce\ECommerceFeature;
use Doctrine\Tests\Models\ECommerce\ECommerceProduct;
use Doctrine\Tests\OrmFunctionalTestCase;
use ReflectionClass;

use const PHP_VERSION_ID;

/**
 * Tests capabilities of the persister.
 */
class StandardEntityPersisterTest extends OrmFunctionalTestCase
{
    protected function setUp(): void
    {
        $this->useModelSet('ecommerce');
        $this->useModelSet('cms');

        parent::setUp();
    }

    public function testAcceptsForeignKeysAsCriteria(): void
    {
        $customer = new ECommerceCustomer();
        $customer->setName('John Doe');
        $cart = new ECommerceCart();
        $cart->setPayment('Credit card');
        $customer->setCart($cart);
        $this->_em->persist($customer);
        $this->_em->flush();
        $this->_em->clear();
        $cardId = $cart->getId();
        unset($cart);

        $class = $this->_em->getClassMetadata(ECommerceCart::class);

        $persister = $this->_em->getUnitOfWork()->getEntityPersister(ECommerceCart::class);
        $newCart   = new ECommerceCart();
        $this->_em->getUnitOfWork()->registerManaged($newCart, ['id' => $cardId], []);
        $persister->load(['customer_id' => $customer->getId()], $newCart, $class->associationMappings['customer']);
        self::assertEquals('Credit card', $newCart->getPayment());
    }

    /**
     * Ticket #2478 from Damon Jones (dljones)
     */
    public function testAddPersistRetrieve(): void
    {
        $f1 = new ECommerceFeature();
        $f1->setDescription('AC-3');

        $f2 = new ECommerceFeature();
        $f2->setDescription('DTS');

        $p = new ECommerceProduct();
        $p->addFeature($f1);
        $p->addFeature($f2);
        $this->_em->persist($p);

        $this->_em->flush();

        self::assertCount(2, $p->getFeatures());
        self::assertInstanceOf(PersistentCollection::class, $p->getFeatures());

        $q = $this->_em->createQuery(
            'SELECT p, f
               FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p
               JOIN p.features f',
        );

        $res = $q->getResult();

        self::assertCount(2, $p->getFeatures());
        self::assertInstanceOf(PersistentCollection::class, $p->getFeatures());

        // Check that the features are the same instances still
        foreach ($p->getFeatures() as $feature) {
            if ($feature->getDescription() === 'AC-3') {
                self::assertSame($feature, $f1);
            } else {
                self::assertSame($feature, $f2);
            }
        }

        // Now we test how Hydrator affects IdentityMap
        // (change from ArrayCollection to PersistentCollection)
        $f3 = new ECommerceFeature();
        $f3->setDescription('XVID');
        $p->addFeature($f3);

        // Now we persist the Feature #3
        $this->_em->persist($p);
        $this->_em->flush();

        $q = $this->_em->createQuery(
            'SELECT p, f
               FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p
               JOIN p.features f',
        );

        $res = $q->getResult();

        // Persisted Product now must have 3 Feature items
        self::assertCount(3, $res[0]->getFeatures());
    }

    public function testPersistLazyGhost(): void
    {
        if (PHP_VERSION_ID < 80400) {
            $this->markTestSkipped('Lazy objects are only available in PHP 8.4+.');
        }

        $initialized = false;
        $reflector   = new ReflectionClass(CmsUser::class);
        $lazyGhost   = $reflector->newLazyGhost(static function (CmsUser $object) use (&$initialized): void {
            $initialized      = true;
            $object->username = 'lazyGhost';
            $object->name     = 'LazyGhostInitialized';
            $object->status   = 'active';
        });

        self::assertFalse($initialized, 'Lazy ghost should not be initialized before persist.');
        $this->_em->persist($lazyGhost);
        $this->_em->flush();
        self::assertTrue($initialized, 'Lazy ghost should be initialized during flush.');
        $this->_em->clear();
        $retrievedEntity = $this->_em->find(CmsUser::class, $lazyGhost->id);
        self::assertNotNull($retrievedEntity);
        self::assertEquals('LazyGhostInitialized', $retrievedEntity->name);
    }
}
