<?php

declare(strict_types=1);

namespace App\Tests\Module\Directory;

use ApiPlatform\Metadata\Post;
use App\Module\Directory\Domain\Entity\Address;
use App\Module\Directory\Domain\Entity\CommercialReport;
use App\Module\Directory\Domain\Entity\Contact;
use App\Module\Directory\Domain\Entity\Prospect;
use App\Module\Directory\Domain\Enum\ReportType;
use App\Module\Directory\Infrastructure\ApiPlatform\State\ConvertProspectProcessor;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @internal
 */
final class ConvertProspectProcessorTest extends KernelTestCase
{
    public function testConvertReassignsContactsAddressesAndReports(): void
    {
        self::bootKernel();

        /** @var EntityManagerInterface $em */
        $em = self::getContainer()->get(EntityManagerInterface::class);

        $prospect = new Prospect();
        $prospect->setCompany('Atelier Test SARL');
        $em->persist($prospect);

        $contact = new Contact()->setLastName('Durand')->setProspect($prospect);
        $address = new Address()->setCity('Niort')->setProspect($prospect);
        $report  = new CommercialReport()
            ->setSubject('Premier contact')
            ->setOccurredAt(new DateTimeImmutable('2026-06-01'))
            ->setType(ReportType::Call)
            ->setProspect($prospect)
        ;
        $em->persist($contact);
        $em->persist($address);
        $em->persist($report);
        $em->flush();

        $processor = self::getContainer()->get(ConvertProspectProcessor::class);
        $operation = new Post();
        $processor->process($prospect, $operation, ['id' => $prospect->getId()]);

        $em->refresh($contact);
        $em->refresh($address);
        $em->refresh($report);

        $client = $prospect->getConvertedClient();
        self::assertNotNull($client, 'Prospect should be converted to a client');

        // Invariants (pas de counts absolus) : chaque sous-entité pointe vers le client, plus vers le prospect.
        self::assertSame($client->getId(), $contact->getClient()?->getId());
        self::assertNull($contact->getProspect());
        self::assertSame($client->getId(), $address->getClient()?->getId());
        self::assertNull($address->getProspect());
        self::assertSame($client->getId(), $report->getClient()?->getId());
        self::assertNull($report->getProspect());
    }
}
