<?php

declare(strict_types=1);

namespace App\Tests\Module\Transport\Api;

use Doctrine\DBAL\Connection;

/**
 * Tests Audit du repertoire transporteurs (M4, spec § 6). Couvre :
 *  - POST / PATCH / archivage -> ligne audit_log entity_type='transport.Carrier'
 *    avec l'action et le diff attendus ;
 *  - le diff d'archivage trace bien le champ `isArchived` (RG-4.14).
 *
 * Jumeau de {@see \App\Tests\Module\Commercial\Api\SupplierAuditTest}.
 *
 * @internal
 */
final class CarrierAuditTest extends AbstractCarrierApiTestCase
{
    private const string CARRIER_TYPE = 'transport.Carrier';

    private ?Connection $auditConnection = null;

    protected function setUp(): void
    {
        parent::setUp();
        self::bootKernel();

        /** @var Connection $conn */
        $conn                  = self::getContainer()->get('doctrine.dbal.audit_connection');
        $this->auditConnection = $conn;
    }

    protected function tearDown(): void
    {
        if (null !== $this->auditConnection) {
            $this->auditConnection->close();
        }
        parent::tearDown();
    }

    public function testPostCarrierIsAudited(): void
    {
        $admin = $this->createAdminClient();

        $created = $admin->request('POST', '/api/carriers', [
            'headers' => ['Content-Type' => self::LD],
            'json'    => $this->validMainPayload('Audit Created Co'),
        ])->toArray();
        self::assertResponseStatusCodeSame(201);

        self::assertGreaterThanOrEqual(
            1,
            $this->countAudit(self::CARRIER_TYPE, (string) $created['id'], 'create'),
            'Un audit_log "create" doit etre genere pour le transporteur.',
        );
    }

    public function testPatchCarrierIsAudited(): void
    {
        $admin = $this->createAdminClient();
        $seed  = $this->seedCarrier('Audit Patch Co');

        $admin->request('PATCH', '/api/carriers/'.$seed->getId(), [
            'headers' => ['Content-Type' => self::MERGE],
            'json'    => ['name' => 'Audit Patch Renamed'],
        ]);
        self::assertResponseStatusCodeSame(200);

        self::assertGreaterThanOrEqual(
            1,
            $this->countAudit(self::CARRIER_TYPE, (string) $seed->getId(), 'update'),
            'Un audit_log "update" doit etre genere pour le PATCH.',
        );
    }

    public function testArchiveCarrierIsAudited(): void
    {
        $admin = $this->createAdminClient();
        $seed  = $this->seedCarrier('Audit Archive Co');

        $admin->request('PATCH', '/api/carriers/'.$seed->getId(), [
            'headers' => ['Content-Type' => self::MERGE],
            'json'    => ['isArchived' => true],
        ]);
        self::assertResponseStatusCodeSame(200);

        $rows = $this->auditConnection->fetchAllAssociative(
            'SELECT changes FROM audit_log WHERE entity_type = :type AND entity_id = :id AND action = :action ORDER BY performed_at DESC',
            ['type' => self::CARRIER_TYPE, 'id' => (string) $seed->getId(), 'action' => 'update'],
        );
        self::assertGreaterThanOrEqual(1, count($rows));

        /** @var array<string, mixed> $changes */
        $changes = json_decode((string) $rows[0]['changes'], true, flags: JSON_THROW_ON_ERROR);
        self::assertArrayHasKey('isArchived', $changes, 'Le diff d\'archivage doit tracer isArchived (RG-4.14).');
    }

    private function countAudit(string $type, string $id, string $action): int
    {
        return (int) $this->auditConnection->fetchOne(
            'SELECT COUNT(*) FROM audit_log WHERE entity_type = :type AND entity_id = :id AND action = :action',
            ['type' => $type, 'id' => $id, 'action' => $action],
        );
    }
}
