<?php

declare(strict_types=1);

namespace App\Tests\Module\Commercial\Api;

use App\Module\Commercial\Domain\Entity\Client as ClientEntity;
use App\Module\Commercial\Domain\Entity\ClientAddress;
use App\Module\Commercial\Domain\Entity\ClientContact;
use App\Module\Commercial\Domain\Entity\ClientRib;
use App\Module\Commercial\Domain\Entity\PaymentType;
use App\Module\Sites\Domain\Entity\Site;

/**
 * Tests fonctionnels des sous-ressources Contacts / Adresses / RIB (ERP-57,
 * spec § 4.5). Couvrent : CRUD via admin, normalisation serveur
 * (RG-1.19/1.20/1.21), validations (Assert\Count sites RG-1.10, Assert\Iban/Bic),
 * regles metier RG-1.13 (DELETE dernier RIB sous LCR -> 409) et RG-1.14 (DELETE
 * dernier contact -> 409), plus le gating comptable (POST/PATCH/DELETE de
 * client_ribs sans accounting.manage -> 403).
 *
 * @internal
 */
final class ClientSubResourceApiTest extends AbstractCommercialApiTestCase
{
    private const string LD         = 'application/ld+json';
    private const string MERGE      = 'application/merge-patch+json';
    private const string VALID_IBAN = 'FR1420041010050500013M02606';
    private const string VALID_BIC  = 'BNPAFRPPXXX';
    // BIC allemand valide isolement (pays DE en positions 5-6) : sert au controle
    // croise pays BIC/IBAN (DE vs IBAN FR -> mismatch, cf. Assert\Bic ibanPropertyPath).
    private const string FOREIGN_BIC = 'DEUTDEFFXXX';

    // === Contacts ===

    public function testPostContactNormalizesFields(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Contact Host');

        $data = $client->request('POST', '/api/clients/'.$seed->getId().'/contacts', [
            'headers' => ['Content-Type' => self::LD],
            'json'    => [
                'firstName'    => 'JEAN',
                'lastName'     => 'dupont',
                'phonePrimary' => '06.12.34.56.78',
                'email'        => 'Jean.DUPONT@ACME.FR',
            ],
        ])->toArray();

        self::assertResponseStatusCodeSame(201);
        // RG-1.19 / 1.20 / 1.21
        self::assertSame('Jean', $data['firstName']);
        self::assertSame('Dupont', $data['lastName']);
        self::assertSame('0612345678', $data['phonePrimary']);
        self::assertSame('jean.dupont@acme.fr', $data['email']);
    }

    public function testPostContactWithoutNameReturns422(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Contact No Name');

        $client->request('POST', '/api/clients/'.$seed->getId().'/contacts', [
            'headers' => ['Content-Type' => self::LD],
            'json'    => ['jobTitle' => 'Directeur'],
        ]);

        // RG-1.05
        self::assertResponseStatusCodeSame(422);
    }

    /**
     * ERP-107 : une violation de contrainte sort avec un message FR explicite ET
     * un `propertyPath` rattache au champ (consommable par useFormErrors /
     * mapViolationsToRecord cote front, ERP-101). On verifie le JSON 422 reel.
     */
    public function testPostContactInvalidEmailReturns422WithFrenchMessageOnField(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Contact Bad Email');

        $response = $client->request('POST', '/api/clients/'.$seed->getId().'/contacts', [
            'headers' => ['Content-Type' => self::LD, 'Accept' => self::LD],
            'json'    => [
                'firstName' => 'Jean',
                'email'     => 'pas-un-email',
            ],
        ]);

        self::assertResponseStatusCodeSame(422);
        $byPath = $this->violationsByPath($response->toArray(false));

        self::assertArrayHasKey('email', $byPath, 'La violation email doit porter propertyPath=email (mapping front).');
        self::assertSame('L\'adresse email n\'est pas valide.', $byPath['email']);
    }

    /**
     * Regression ERP-110 (bug subresource Link toProperty) : POST d'un contact sur
     * un client qui en a DEJA >= 2 ne doit pas exploser en 500
     * (NonUniqueResultException sur la resolution du parent), mais creer (201).
     */
    public function testPostContactOnClientWithTwoExistingContactsReturns201(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Contact Multi');
        $this->seedContact($seed, 'Alpha');
        $this->seedContact($seed, 'Beta');

        $client->request('POST', '/api/clients/'.$seed->getId().'/contacts', [
            'headers' => ['Content-Type' => self::LD, 'Accept' => self::LD],
            'json'    => ['firstName' => 'Gamma'],
        ]);

        self::assertResponseStatusCodeSame(201);
    }

    /**
     * Meme contexte (>= 2 contacts existants) : un email invalide doit produire
     * une 422 par champ (la validation est bien atteinte), pas une 500.
     */
    public function testPostInvalidContactOnPopulatedClientReturns422OnField(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Contact Multi Bad');
        $this->seedContact($seed, 'Alpha');
        $this->seedContact($seed, 'Beta');

        $response = $client->request('POST', '/api/clients/'.$seed->getId().'/contacts', [
            'headers' => ['Content-Type' => self::LD, 'Accept' => self::LD],
            'json'    => ['firstName' => 'Gamma', 'email' => 'pas-un-email'],
        ]);

        self::assertResponseStatusCodeSame(422);
        $byPath = $this->violationsByPath($response->toArray(false));
        self::assertArrayHasKey('email', $byPath);
        self::assertSame('L\'adresse email n\'est pas valide.', $byPath['email']);
    }

    /**
     * ERP-110 : avec read:false sur le POST, un parent introuvable n'est plus
     * intercepte au stade lecture. Le 404 est desormais porte par
     * ClientContactProcessor::linkParent (sinon 500 au persist sur client_id
     * NOT NULL). Le payload est valide pour atteindre le processor (apres la
     * validation).
     */
    public function testPostContactOnMissingClientReturns404(): void
    {
        $client = $this->createAdminClient();

        $client->request('POST', '/api/clients/999999/contacts', [
            'headers' => ['Content-Type' => self::LD, 'Accept' => self::LD],
            'json'    => ['firstName' => 'Orphan'],
        ]);

        self::assertResponseStatusCodeSame(404);
    }

    public function testPatchContactNormalizes(): void
    {
        $client  = $this->createAdminClient();
        $seed    = $this->seedClient('Contact Patch');
        $contact = $this->seedContact($seed, 'Paul');

        $data = $client->request('PATCH', '/api/client_contacts/'.$contact->getId(), [
            'headers' => ['Content-Type' => self::MERGE],
            'json'    => ['lastName' => 'martin'],
        ])->toArray();

        self::assertResponseStatusCodeSame(200);
        self::assertSame('Martin', $data['lastName']);
    }

    public function testDeleteContactWhenSeveralReturns204(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Contact Multi');
        $this->seedContact($seed, 'Premier');
        $second = $this->seedContact($seed, 'Second');

        $client->request('DELETE', '/api/client_contacts/'.$second->getId());

        self::assertResponseStatusCodeSame(204);
    }

    public function testDeleteLastContactReturns409(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Contact Solo');
        $only   = $this->seedContact($seed, 'Unique');

        $client->request('DELETE', '/api/client_contacts/'.$only->getId());

        // RG-1.14
        self::assertResponseStatusCodeSame(409);
    }

    // === Adresses ===

    public function testPostAddressNormalizesBillingEmail(): void
    {
        $this->skipIfSitesModuleDisabled();
        $client   = $this->createAdminClient();
        $seed     = $this->seedClient('Address Host');
        $siteIri  = $this->firstSiteIri();
        $category = $this->createCategory('SECTEUR');

        $data = $client->request('POST', '/api/clients/'.$seed->getId().'/addresses', [
            'headers' => ['Content-Type' => self::LD],
            'json'    => [
                'isBilling'    => true,
                'billingEmail' => 'Facturation@ACME.FR',
                'postalCode'   => '86100',
                'city'         => 'Châtellerault',
                'street'       => '1 rue du Test',
                'sites'        => [$siteIri],
                'categories'   => ['/api/categories/'.$category->getId()],
            ],
        ])->toArray();

        self::assertResponseStatusCodeSame(201);
        // RG-1.21
        self::assertSame('facturation@acme.fr', $data['billingEmail']);
    }

    public function testPostAddressWithoutSiteReturns422(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Address No Site');

        $client->request('POST', '/api/clients/'.$seed->getId().'/addresses', [
            'headers' => ['Content-Type' => self::LD],
            'json'    => [
                'isDelivery' => true,
                'postalCode' => '86100',
                'city'       => 'Châtellerault',
                'street'     => '1 rue du Test',
                'sites'      => [],
            ],
        ]);

        // RG-1.10 (Assert\Count min 1)
        self::assertResponseStatusCodeSame(422);
    }

    public function testPostAddressWithInvalidPostalCodeReturns422(): void
    {
        $this->skipIfSitesModuleDisabled();
        $client  = $this->createAdminClient();
        $seed    = $this->seedClient('Address Bad CP');
        $siteIri = $this->firstSiteIri();

        $client->request('POST', '/api/clients/'.$seed->getId().'/addresses', [
            'headers' => ['Content-Type' => self::LD],
            'json'    => [
                'isDelivery' => true,
                'postalCode' => '123',
                'city'       => 'Châtellerault',
                'street'     => '1 rue du Test',
                'sites'      => [$siteIri],
            ],
        ]);

        // RG-1.09 (Assert\Regex ^[0-9]{4,5}$)
        self::assertResponseStatusCodeSame(422);
    }

    /**
     * Regression ERP-110 : POST d'une adresse sur un client qui en a DEJA >= 2 ne
     * doit pas exploser en 500 (NonUniqueResult sur la resolution du parent). Le
     * POST porte un site + une categorie (RG-1.10 / RG-1.29) pour etre valide.
     */
    public function testPostAddressOnClientWithTwoExistingAddressesReturns201(): void
    {
        $this->skipIfSitesModuleDisabled();
        $client   = $this->createAdminClient();
        $seed     = $this->seedClient('Addr Multi');
        $siteIri  = $this->firstSiteIri();
        $category = $this->createCategory('SECTEUR');
        $this->seedAddress($seed, 'Bordeaux');
        $this->seedAddress($seed, 'Lyon');

        $client->request('POST', '/api/clients/'.$seed->getId().'/addresses', [
            'headers' => ['Content-Type' => self::LD, 'Accept' => self::LD],
            'json'    => [
                'isDelivery' => true,
                'postalCode' => '75001',
                'city'       => 'Paris',
                'street'     => '2 rue Neuve',
                'sites'      => [$siteIri],
                'categories' => ['/api/categories/'.$category->getId()],
            ],
        ]);

        self::assertResponseStatusCodeSame(201);
    }

    /**
     * ERP-110 : POST adresse sur un client inexistant -> 404 porte par
     * ClientAddressProcessor::linkParent (read:false). Payload valide (site +
     * categorie, RG-1.10 / RG-1.29) pour atteindre le processor.
     */
    public function testPostAddressOnMissingClientReturns404(): void
    {
        $this->skipIfSitesModuleDisabled();
        $client   = $this->createAdminClient();
        $siteIri  = $this->firstSiteIri();
        $category = $this->createCategory('SECTEUR');

        $client->request('POST', '/api/clients/999999/addresses', [
            'headers' => ['Content-Type' => self::LD, 'Accept' => self::LD],
            'json'    => [
                'isDelivery' => true,
                'postalCode' => '75001',
                'city'       => 'Paris',
                'street'     => '2 rue Neuve',
                'sites'      => [$siteIri],
                'categories' => ['/api/categories/'.$category->getId()],
            ],
        ]);

        self::assertResponseStatusCodeSame(404);
    }

    // === RIBs ===

    public function testPostRibByAdminReturns201(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Rib Host');

        $data = $client->request('POST', '/api/clients/'.$seed->getId().'/ribs', [
            'headers' => ['Content-Type' => self::LD],
            'json'    => [
                'label' => 'Compte principal',
                'bic'   => self::VALID_BIC,
                'iban'  => self::VALID_IBAN,
            ],
        ])->toArray();

        self::assertResponseStatusCodeSame(201);
        self::assertSame('Compte principal', $data['label']);
    }

    public function testPostRibWithInvalidIbanReturns422(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Rib Bad Iban');

        $client->request('POST', '/api/clients/'.$seed->getId().'/ribs', [
            'headers' => ['Content-Type' => self::LD],
            'json'    => [
                'label' => 'Compte invalide',
                'bic'   => self::VALID_BIC,
                'iban'  => 'INVALID-IBAN',
            ],
        ]);

        // Assert\Iban
        self::assertResponseStatusCodeSame(422);
    }

    /**
     * Controle croise pays BIC/IBAN (Assert\Bic ibanPropertyPath) : un BIC (DE) et
     * un IBAN (FR) valides isolement mais de pays differents -> 422. La violation
     * porte propertyPath=bic et le message FR `ibanMessage` (mapping inline front).
     */
    public function testPostRibWithBicIbanCountryMismatchReturns422WithFrenchMessageOnBic(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Rib Pays Mismatch');

        $response = $client->request('POST', '/api/clients/'.$seed->getId().'/ribs', [
            'headers' => ['Content-Type' => self::LD, 'Accept' => self::LD],
            'json'    => [
                'label' => 'Compte incoherent',
                'bic'   => self::FOREIGN_BIC,
                'iban'  => self::VALID_IBAN,
            ],
        ]);

        self::assertResponseStatusCodeSame(422);
        $byPath = $this->violationsByPath($response->toArray(false));

        self::assertArrayHasKey('bic', $byPath, 'Le mismatch pays BIC/IBAN doit porter propertyPath=bic (mapping front).');
        self::assertSame('Le BIC ne correspond pas au pays de l\'IBAN.', $byPath['bic']);
    }

    /**
     * Regression ERP-110 : POST d'un RIB sur un client qui en a DEJA >= 2 ne doit
     * pas exploser en 500 (NonUniqueResult sur la resolution du parent). L'admin
     * porte commercial.clients.accounting.manage requis par le POST.
     */
    public function testPostRibOnClientWithTwoExistingRibsReturns201(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Rib Multi');
        $this->seedRib($seed, 'Compte 1');
        $this->seedRib($seed, 'Compte 2');

        $client->request('POST', '/api/clients/'.$seed->getId().'/ribs', [
            'headers' => ['Content-Type' => self::LD, 'Accept' => self::LD],
            'json'    => ['label' => 'Compte 3', 'bic' => self::VALID_BIC, 'iban' => self::VALID_IBAN],
        ]);

        self::assertResponseStatusCodeSame(201);
    }

    /**
     * ERP-110 : POST RIB sur un client inexistant -> 404 porte par
     * ClientRibProcessor::linkParent (read:false). L'admin porte
     * commercial.clients.accounting.manage ; payload valide (BIC / IBAN).
     */
    public function testPostRibOnMissingClientReturns404(): void
    {
        $client = $this->createAdminClient();

        $client->request('POST', '/api/clients/999999/ribs', [
            'headers' => ['Content-Type' => self::LD, 'Accept' => self::LD],
            'json'    => ['label' => 'Orphan', 'bic' => self::VALID_BIC, 'iban' => self::VALID_IBAN],
        ]);

        self::assertResponseStatusCodeSame(404);
    }

    public function testDeleteRibNonLcrReturns204(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Rib Non LCR');
        $rib    = $this->seedRib($seed);

        $client->request('DELETE', '/api/client_ribs/'.$rib->getId());

        self::assertResponseStatusCodeSame(204);
    }

    public function testDeleteLastRibUnderLcrReturns409(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Rib LCR Solo');
        $this->setPaymentType($seed, 'LCR');
        $rib = $this->seedRib($seed);

        $client->request('DELETE', '/api/client_ribs/'.$rib->getId());

        // RG-1.13
        self::assertResponseStatusCodeSame(409);
    }

    public function testRibWriteWithoutAccountingManageReturns403(): void
    {
        // Un utilisateur portant seulement commercial.clients.manage (sans
        // accounting.manage) ne peut ni creer, ni modifier, ni supprimer un RIB.
        $seed        = $this->seedClient('Rib Forbidden');
        $rib         = $this->seedRib($seed);
        $credentials = $this->createUserWithPermission('commercial.clients.manage');
        $client      = $this->authenticatedClient($credentials['username'], $credentials['password']);

        $client->request('POST', '/api/clients/'.$seed->getId().'/ribs', [
            'headers' => ['Content-Type' => self::LD],
            'json'    => ['label' => 'X', 'bic' => self::VALID_BIC, 'iban' => self::VALID_IBAN],
        ]);
        self::assertResponseStatusCodeSame(403);

        $client->request('PATCH', '/api/client_ribs/'.$rib->getId(), [
            'headers' => ['Content-Type' => self::MERGE],
            'json'    => ['label' => 'Y'],
        ]);
        self::assertResponseStatusCodeSame(403);

        $client->request('DELETE', '/api/client_ribs/'.$rib->getId());
        self::assertResponseStatusCodeSame(403);
    }

    // === Helpers ===

    /**
     * Seede un ClientContact rattache a un client (sans passer par l'API).
     */
    private function seedContact(ClientEntity $client, string $firstName): ClientContact
    {
        $em      = $this->getEm();
        $contact = new ClientContact();
        $contact->setFirstName($firstName);
        $contact->setClient($client);
        $em->persist($contact);
        $em->flush();

        return $contact;
    }

    /**
     * Seede une adresse minimale valide en base (sans passer par l'API) : seules
     * les colonnes NOT NULL sont posees (CP / ville / rue). Les M2M sites /
     * categories restent vides — non contraints en base, suffisant pour peupler
     * un client de plusieurs adresses.
     */
    private function seedAddress(ClientEntity $client, string $city): ClientAddress
    {
        $em      = $this->getEm();
        $address = new ClientAddress();
        $address->setClient($client);
        $address->setPostalCode('33000');
        $address->setCity($city);
        $address->setStreet('1 rue du Test');
        $em->persist($address);
        $em->flush();

        return $address;
    }

    /**
     * Seede un ClientRib valide rattache a un client (sans passer par l'API). Le
     * libelle est parametrable pour seeder plusieurs RIB distincts.
     */
    private function seedRib(ClientEntity $client, string $label = 'Seed RIB'): ClientRib
    {
        $em  = $this->getEm();
        $rib = new ClientRib();
        $rib->setLabel($label);
        $rib->setBic(self::VALID_BIC);
        $rib->setIban(self::VALID_IBAN);
        $rib->setClient($client);
        $em->persist($rib);
        $em->flush();

        return $rib;
    }

    /**
     * Affecte un type de reglement (par code) au client seede.
     */
    private function setPaymentType(ClientEntity $client, string $code): void
    {
        $em   = $this->getEm();
        $type = $em->getRepository(PaymentType::class)->findOneBy(['code' => $code]);
        self::assertNotNull($type, sprintf('PaymentType "%s" introuvable (fixtures).', $code));

        $managed = $em->getRepository(ClientEntity::class)->find($client->getId());
        $managed->setPaymentType($type);
        $em->flush();
    }

    /**
     * Retourne l'IRI du premier site seede (fixtures Sites). Skip en amont si le
     * module Sites est desactive.
     */
    private function firstSiteIri(): string
    {
        $site = $this->getEm()->getRepository(Site::class)->findOneBy([]);
        self::assertNotNull($site, 'Aucun site seede : impossible de tester les adresses.');

        return '/api/sites/'.$site->getId();
    }
}
