<?php

declare(strict_types=1);

namespace App\Tests\Module\Commercial\Api;

/**
 * Tests de securite GENERIQUE de /api/clients (ERP-60).
 *
 * Couvre les garde-fous non dependants des roles metier :
 *  - 401 si requete anonyme (firewall JWT) ;
 *  - 403 si l'utilisateur authentifie ne porte pas `commercial.clients.view`.
 *
 * ⚠ La matrice RBAC differenciee par role metier (bureau / compta / commerciale
 * / usine) est DELEGUEE a ERP-74 (#493) : elle exige les roles seedes apres le
 * merge de la stack. NE PAS l'ajouter ici.
 *
 * @internal
 */
final class ClientSecurityTest extends AbstractCommercialApiTestCase
{
    private const string LD = 'application/ld+json';

    public function testAnonymousGetCollectionReturns401(): void
    {
        $client = self::createClient();
        $client->request('GET', '/api/clients', ['headers' => ['Accept' => self::LD]]);

        self::assertResponseStatusCodeSame(401);
    }

    public function testAnonymousGetItemReturns401(): void
    {
        $seed   = $this->seedClient('Anon Item');
        $client = self::createClient();

        $client->request('GET', '/api/clients/'.$seed->getId(), ['headers' => ['Accept' => self::LD]]);

        self::assertResponseStatusCodeSame(401);
    }

    public function testForbiddenWithoutClientsViewPermission(): void
    {
        // User authentifie portant une permission SANS rapport avec les clients.
        $seed        = $this->seedClient('Forbidden Target');
        $credentials = $this->createUserWithPermission('core.users.view');
        $client      = $this->authenticatedClient($credentials['username'], $credentials['password']);

        // Collection.
        $client->request('GET', '/api/clients', ['headers' => ['Accept' => self::LD]]);
        self::assertResponseStatusCodeSame(403);

        // Detail.
        $client->request('GET', '/api/clients/'.$seed->getId(), ['headers' => ['Accept' => self::LD]]);
        self::assertResponseStatusCodeSame(403);
    }
}
