<?php

declare(strict_types=1);

namespace App\Tests\Functional\Module\Core;

use App\Module\Core\Domain\Entity\Role;
use App\Module\Core\Domain\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

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

        self::assertResponseStatusCodeSame(401);
    }

    public function testAdminCanListRoles(): void
    {
        $client = self::createClient();
        $this->loginAdmin($client);

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

        self::assertResponseIsSuccessful();
        $data = json_decode($client->getResponse()->getContent(), true);
        self::assertArrayHasKey('member', $data);
    }

    public function testAdminCanCreateRole(): void
    {
        $client = self::createClient();
        $this->loginAdmin($client);

        $code = 'bureau_'.uniqid();
        $client->request('POST', '/api/roles', server: [
            'CONTENT_TYPE' => 'application/ld+json',
        ], content: json_encode(['code' => $code, 'label' => 'Bureau']));

        self::assertResponseStatusCodeSame(201);
        $data = json_decode($client->getResponse()->getContent(), true);
        self::assertSame($code, $data['code']);
        self::assertSame('Bureau', $data['label']);
        self::assertFalse($data['isSystem']);
    }

    public function testDeletingSystemRoleIsForbidden(): void
    {
        $client = self::createClient();
        $em     = self::getContainer()->get(EntityManagerInterface::class);

        $systemRole = new Role('sys_'.uniqid(), 'System role', 'Rôle système', true);
        $em->persist($systemRole);
        $em->flush();
        $id = $systemRole->getId();

        $this->loginAdmin($client);

        $client->request('DELETE', '/api/roles/'.$id);

        self::assertResponseStatusCodeSame(403);
    }

    private function loginAdmin(KernelBrowser $client): void
    {
        $em   = self::getContainer()->get(EntityManagerInterface::class);
        $user = $em->getRepository(User::class)->findOneBy(['username' => 'admin']);
        self::assertInstanceOf(User::class, $user);
        $client->loginUser($user);
    }
}
