<?php

declare(strict_types=1);

namespace App\Tests\Module\Sites\Api;

use App\Module\Sites\Domain\Entity\Site;
use App\Tests\Module\Core\Api\AbstractApiTestCase;

/**
 * Tests fonctionnels de l'endpoint PATCH /api/me/current-site (switch).
 *
 * Fixtures utilisees :
 *  - alice : rattachee a Chatellerault uniquement (currentSite = Chatellerault).
 *  - admin : rattache aux 3 sites.
 *  - bob : rattache a Saint-Jean uniquement.
 *
 * @internal
 */
final class CurrentSiteSwitchApiTest extends AbstractApiTestCase
{
    public function testUserCanSwitchToAuthorizedSite(): void
    {
        // admin a les 3 sites. On le bascule de Chatellerault vers Pommevic.
        $em       = $this->getEm();
        $pommevic = $em->getRepository(Site::class)->findOneBy(['name' => 'Pommevic']);
        self::assertNotNull($pommevic);

        $client   = $this->authenticatedClient('admin', 'admin');
        $response = $client->request('PATCH', '/api/me/current-site', [
            'headers' => ['Content-Type' => 'application/merge-patch+json'],
            'json'    => ['site' => '/api/sites/'.$pommevic->getId()],
        ]);

        self::assertResponseIsSuccessful();
        $data = $response->toArray();
        self::assertSame('Pommevic', $data['currentSite']['name']);
    }

    public function testUserCannotSwitchToUnauthorizedSite(): void
    {
        // alice n'a que Chatellerault. Tenter Pommevic → 400 (anti-enumeration).
        //
        // Depuis l'ajout de SiteCollectionScopedExtension, les sites hors
        // du scope de l'user sont filtres a la source : l'IriConverter ne
        // peut pas resoudre `/api/sites/{id}` pour un site non autorise et
        // leve 400 "Item not found". Reponse identique a "site inexistant",
        // ce qui empeche l'enumeration des ids de sites tiers. Avant la PR
        // scope, le processor traduisait SiteNotAuthorizedException → 403.
        $em       = $this->getEm();
        $pommevic = $em->getRepository(Site::class)->findOneBy(['name' => 'Pommevic']);
        self::assertNotNull($pommevic);

        $client = $this->authenticatedClient('alice', 'alice');
        $client->request('PATCH', '/api/me/current-site', [
            'headers' => ['Content-Type' => 'application/merge-patch+json'],
            'json'    => ['site' => '/api/sites/'.$pommevic->getId()],
        ]);

        self::assertResponseStatusCodeSame(400);
    }

    public function testSwitchWithMissingSiteFieldReturns400(): void
    {
        $client = $this->authenticatedClient('alice', 'alice');
        $client->request('PATCH', '/api/me/current-site', [
            'headers' => ['Content-Type' => 'application/merge-patch+json'],
            'json'    => [],
        ]);

        self::assertResponseStatusCodeSame(400);
    }

    public function testAnonymousUserCannotSwitch(): void
    {
        $client = self::createClient();
        $client->request('PATCH', '/api/me/current-site', [
            'headers' => ['Content-Type' => 'application/merge-patch+json'],
            'json'    => ['site' => '/api/sites/1'],
        ]);

        self::assertResponseStatusCodeSame(401);
    }

    public function testSwitchWithNonExistentSiteIriReturnsErrorStatus(): void
    {
        // IRI vers un site qui n'existe pas en base : API Platform leve un
        // 400 Bad Request a la denormalisation (l'IriConverter ne peut pas
        // resoudre l'IRI). On grave le code de retour reel pour eviter
        // qu'une regression silencieuse passe inapercue.
        $client = $this->authenticatedClient('alice', 'alice');
        $client->request('PATCH', '/api/me/current-site', [
            'headers' => ['Content-Type' => 'application/merge-patch+json'],
            'json'    => ['site' => '/api/sites/999999'],
        ]);

        self::assertResponseStatusCodeSame(400);
    }
}
