<?php

declare(strict_types=1);

namespace App\Tests\Module\Commercial\Api;

/**
 * Validation back-autoritative du FORMAT de la date de creation (foundedAt,
 * onglet Information).
 *
 * Le front (MalioDate, cf. MUI-44) forwarde desormais la saisie brute invalide
 * au serveur plutot que de l'avaler. Cote back, une date non parsable doit
 * produire un 422 porte sur `foundedAt` (mappable inline par useFormErrors),
 * et non un 400 generique. Repose sur `collectDenormalizationErrors` actif sur
 * l'operation Patch du Client.
 *
 * @internal
 */
final class ClientFoundedAtFormatTest extends AbstractCommercialApiTestCase
{
    private const string MERGE = 'application/merge-patch+json';

    /** Date non parsable -> 422 porte sur foundedAt (et pas un 400 generique). */
    public function testFoundedAtNonParsableEst422(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Founded Format SARL');

        $body = $client->request('PATCH', '/api/clients/'.$seed->getId(), [
            'headers' => ['Content-Type' => self::MERGE],
            'json'    => ['foundedAt' => '32/13/2026'],
        ])->toArray(false);

        self::assertResponseStatusCodeSame(422);
        self::assertArrayHasKey('foundedAt', $this->violationsByPath($body));
    }

    /**
     * Cas piege : « 12/25/2026 » est invalide cote front (JJ/MM/AAAA -> mois 25)
     * mais PHP DateTime l'accepterait en M/J/AAAA (25 decembre). Le format d'entree
     * strict ISO `Y-m-d` (Context sur foundedAt) doit le rejeter -> 422.
     */
    public function testFoundedAtFormatAmbiguUsEst422(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Founded Ambigu SARL');

        $body = $client->request('PATCH', '/api/clients/'.$seed->getId(), [
            'headers' => ['Content-Type' => self::MERGE],
            'json'    => ['foundedAt' => '12/25/2026'],
        ])->toArray(false);

        self::assertResponseStatusCodeSame(422);
        self::assertArrayHasKey('foundedAt', $this->violationsByPath($body));
    }

    /** Non-regression : une date ISO valide reste acceptee (200). */
    public function testFoundedAtIsoValideEst200(): void
    {
        $client = $this->createAdminClient();
        $seed   = $this->seedClient('Founded Ok SARL');

        $data = $client->request('PATCH', '/api/clients/'.$seed->getId(), [
            'headers' => ['Content-Type' => self::MERGE],
            'json'    => ['foundedAt' => '2010-05-01'],
        ])->toArray();

        self::assertResponseStatusCodeSame(200);
        self::assertStringStartsWith('2010-05-01', $data['foundedAt']);
    }
}
