<?php

declare(strict_types=1);

namespace App\Tests\Functional\Shared;

use App\Module\Core\Domain\Entity\User;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * @internal
 */
final class SidebarEndpointTest extends WebTestCase
{
    public function testSidebarRequiresAuthentication(): void
    {
        $client = self::createClient();
        $client->request('GET', '/api/sidebar');

        self::assertResponseStatusCodeSame(401);
    }

    public function testSidebarReturnsSectionsForAuthenticatedUser(): void
    {
        $client = self::createClient();
        $em     = self::getContainer()->get('doctrine.orm.entity_manager');

        $user = $em->getRepository(User::class)->findOneBy(['username' => 'alice']);
        $client->loginUser($user);

        $client->request('GET', '/api/sidebar');

        self::assertResponseIsSuccessful();
        $data = json_decode($client->getResponse()->getContent(), true);
        self::assertArrayHasKey('sections', $data);
        self::assertArrayHasKey('disabledRoutes', $data);
        self::assertNotEmpty($data['sections']);
    }

    public function testAdminSectionHiddenForNonAdmin(): void
    {
        $client = self::createClient();
        $em     = self::getContainer()->get('doctrine.orm.entity_manager');

        $user = $em->getRepository(User::class)->findOneBy(['username' => 'alice']); // ROLE_USER
        $client->loginUser($user);

        $client->request('GET', '/api/sidebar');
        $data   = json_decode($client->getResponse()->getContent(), true);
        $labels = array_column($data['sections'], 'label');

        self::assertNotContains('sidebar.admin.section', $labels);
    }

    public function testAdminSectionVisibleForAdmin(): void
    {
        $client = self::createClient();
        $em     = self::getContainer()->get('doctrine.orm.entity_manager');

        $user = $em->getRepository(User::class)->findOneBy(['username' => 'admin']); // ROLE_ADMIN
        $client->loginUser($user);

        $client->request('GET', '/api/sidebar');
        $data   = json_decode($client->getResponse()->getContent(), true);
        $labels = array_column($data['sections'], 'label');

        self::assertContains('sidebar.admin.section', $labels);
    }
}
