<?php

declare(strict_types=1);

namespace App\Tests\Api\Controller;

use App\Tests\AbstractApiTestCase;

/**
 * @internal
 */
class EntityHistoryTest extends AbstractApiTestCase
{
    public function testMachineHistoryAfterCreate(): void
    {
        $machine = $this->createMachine('Machine A');

        $client = $this->createViewerClient();
        $client->request('GET', sprintf('/api/machines/%s/history', $machine->getId()));

        $this->assertResponseIsSuccessful();
        $data = $client->getResponse()->toArray();
        $this->assertArrayHasKey('items', $data);
        $this->assertArrayHasKey('total', $data);
    }

    public function testMachineHistoryAfterUpdate(): void
    {
        $machine = $this->createMachine('Machine A');

        $gClient = $this->createGestionnaireClient();
        $gClient->request('PATCH', self::iri('machines', $machine->getId()), [
            'headers' => ['Content-Type' => 'application/merge-patch+json'],
            'json'    => ['name' => 'Machine A Updated'],
        ]);
        $this->assertResponseIsSuccessful();

        $vClient = $this->createViewerClient();
        $vClient->request('GET', sprintf('/api/machines/%s/history', $machine->getId()));

        $this->assertResponseIsSuccessful();
        $data = $vClient->getResponse()->toArray();
        $this->assertGreaterThanOrEqual(1, $data['total']);
    }

    public function testMachineHistoryNotFound(): void
    {
        $client = $this->createViewerClient();
        $client->request('GET', '/api/machines/nonexistent-id/history');

        $this->assertResponseStatusCodeSame(404);
        $this->assertJsonContains(['message' => 'Machine introuvable.']);
    }

    public function testPieceHistory(): void
    {
        $piece = $this->createPiece('Joint A');

        $client = $this->createViewerClient();
        $client->request('GET', sprintf('/api/pieces/%s/history', $piece->getId()));

        $this->assertResponseIsSuccessful();
    }

    public function testComposantHistory(): void
    {
        $composant = $this->createComposant('Pompe A');

        $client = $this->createViewerClient();
        $client->request('GET', sprintf('/api/composants/%s/history', $composant->getId()));

        $this->assertResponseIsSuccessful();
    }

    public function testProductHistory(): void
    {
        $product = $this->createProduct('Produit A');

        $client = $this->createViewerClient();
        $client->request('GET', sprintf('/api/products/%s/history', $product->getId()));

        $this->assertResponseIsSuccessful();
    }

    public function testHistoryUnauthenticated(): void
    {
        $machine = $this->createMachine('Machine A');

        $client = $this->createUnauthenticatedClient();
        $client->request('GET', sprintf('/api/machines/%s/history', $machine->getId()));

        $this->assertResponseStatusCodeSame(401);
    }
}
