<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\ThirdPartyBundle\Tests\Service;

use Chill\ActivityBundle\Entity\Activity;
use Chill\MainBundle\Entity\Center;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use Chill\ThirdPartyBundle\Entity\ThirdPartyCategory;
use Chill\ThirdPartyBundle\Service\ThirdpartyMergeService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @internal
 *
 * @coversNothing
 */
class ThirdpartyMergeServiceTest extends KernelTestCase
{
    private EntityManagerInterface $em;
    private ThirdpartyMergeService $service;

    protected function setUp(): void
    {
        self::bootKernel();
        $this->em = self::getContainer()->get(EntityManagerInterface::class);

        $this->service = new ThirdpartyMergeService($this->em);
    }

    public function testMergeUpdatesReferencesAndDeletesThirdparty(): void
    {
        // Create ThirdParty entities
        $toKeep = new ThirdParty();
        $toKeep->setName('Thirdparty to keep');
        $this->em->persist($toKeep);

        $toDelete = new ThirdParty();
        $toDelete->setName('Thirdparty to delete');
        $this->em->persist($toDelete);

        // Create a related entity with TO_ONE relation (thirdparty parent) - tests schema handling for TO_ONE
        $relatedToOneEntity = new ThirdParty();
        $relatedToOneEntity->setName('RelatedToOne thirdparty');
        $relatedToOneEntity->setParent($toDelete);
        $this->em->persist($relatedToOneEntity);

        // Create a related entity with MANY_TO_MANY relation (thirdparty category) - tests schema handling for MANY_TO_MANY where ThirdParty is target
        $thirdpartyCategory = new ThirdPartyCategory();
        $thirdpartyCategory->setName(['fr' => 'Thirdparty category']);
        $this->em->persist($thirdpartyCategory);
        $toDelete->addCategory($thirdpartyCategory);
        $this->em->persist($toDelete);

        // Test MANY_TO_MANY relation from another bundle (Activity) - tests cross-bundle schema handling
        $activity = new Activity();
        $activity->setDate(new \DateTime());
        $activity->addThirdParty($toDelete);
        $this->em->persist($activity);

        $this->em->flush();

        // Run merge
        $this->service->merge($toKeep, $toDelete);
        $this->em->refresh($toKeep);
        $this->em->refresh($relatedToOneEntity);

        // Check that references were updated

        // Test TO_ONE relation in chill_3party schema was properly handled
        $this->assertEquals($toKeep->getId(), $relatedToOneEntity->getParent()->getId(), 'The parent thirdparty in chill_3party schema was successfully merged');

        // Test MANY_TO_MANY relation in chill_3party schema was properly handled
        $updatedRelatedManyEntity = $this->em->find(ThirdPartyCategory::class, $thirdpartyCategory->getId());
        $this->assertContains($updatedRelatedManyEntity, $toKeep->getCategories(), 'The thirdparty category in chill_3party schema was found in the toKeep entity');

        // Test MANY_TO_MANY relation from different schema (Activity bundle) was properly handled
        $this->em->refresh($activity);
        $this->assertContains($toKeep, $activity->getThirdParties(), 'The activity relation from different schema was successfully merged');
        $this->assertNotContains($toDelete, $activity->getThirdParties(), 'The toDelete thirdparty was removed from activity relation');

        // Check that toDelete was removed
        $this->em->clear();
        $deletedThirdParty = $this->em->find(ThirdParty::class, $toDelete->getId());
        $this->assertNull($deletedThirdParty, 'The toDelete thirdparty was successfully removed');
    }

    public function testMergeWithSharedCenterDoesNotCauseUniqueConstraintViolation(): void
    {
        // Create a center that will be shared by both thirdparties
        $sharedCenter = new Center();
        $sharedCenter->setName('Shared Center');
        $this->em->persist($sharedCenter);

        // Create ThirdParty entities
        $toKeep = new ThirdParty();
        $toKeep->setName('Thirdparty to keep');
        $toKeep->addCenter($sharedCenter); // Both thirdparties linked to same center
        $this->em->persist($toKeep);

        $toDelete = new ThirdParty();
        $toDelete->setName('Thirdparty to delete');
        $toDelete->addCenter($sharedCenter); // Both thirdparties linked to same center
        $this->em->persist($toDelete);

        $this->em->flush();

        // This should not throw a unique constraint violation
        $this->service->merge($toKeep, $toDelete);

        // Verify that toKeep still has the shared center
        $this->em->refresh($toKeep);
        $this->assertContains($sharedCenter, $toKeep->getCenters(), 'The shared center is still linked to the kept thirdparty');

        // Verify that toDelete was removed
        $this->em->clear();
        $deletedThirdParty = $this->em->find(ThirdParty::class, $toDelete->getId());
        $this->assertNull($deletedThirdParty, 'The toDelete thirdparty was successfully removed');
    }
}
