<?php

declare(strict_types=1);

namespace App\Tests\Api\Controller;

use App\Tests\AbstractApiTestCase;

/**
 * @internal
 */
class CustomFieldNamesControllerTest extends AbstractApiTestCase
{
    public function testReturns401WhenUnauthenticated(): void
    {
        $client = $this->createUnauthenticatedClient();
        $client->request('GET', '/api/custom-fields/names');

        $this->assertResponseStatusCodeSame(401);
    }

    public function testReturnsArrayForAuthenticatedViewer(): void
    {
        $client = $this->createViewerClient();
        $client->request('GET', '/api/custom-fields/names');

        $this->assertResponseIsSuccessful();
        $data = json_decode($client->getResponse()->getContent(), true);
        $this->assertIsArray($data);
    }

    public function testReturnsDistinctSortedNames(): void
    {
        $machine1 = $this->createMachine('M1');
        $this->createCustomField('Tension', 'text', $machine1);
        $this->createCustomField('Numéro de série', 'text', $machine1);

        $machine2 = $this->createMachine('M2');
        $this->createCustomField('Tension', 'text', $machine2); // doublon

        $client = $this->createViewerClient();
        $client->request('GET', '/api/custom-fields/names');

        $this->assertResponseIsSuccessful();
        $data = json_decode($client->getResponse()->getContent(), true);

        $this->assertContains('Tension', $data);
        $this->assertContains('Numéro de série', $data);
        // Pas de doublon
        $this->assertSame(count(array_unique($data)), count($data));
        // Tri alpha
        $sorted = $data;
        sort($sorted, SORT_STRING);
        $this->assertSame($sorted, $data);
    }
}
