<?php

namespace App\Tests\Controller;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class SecurityControllerTest extends WebTestCase
{
    public function testLoginPageReturnsSuccess(): void
    {
        $client = static::createClient();
        $client->request('GET', '/connexion');

        self::assertResponseIsSuccessful();
    }

    public function testLoginRedirectsWhenAuthenticated(): void
    {
        $client = static::createClient();
        $user = $this->createUser();

        $client->loginUser($user);
        $client->request('GET', '/connexion');

        self::assertResponseRedirects();
    }

    public function testChangePasswordRedirectsWhenNotAuthenticated(): void
    {
        $client = static::createClient();
        $client->request('GET', '/mot-de-passe');

        self::assertResponseRedirects();
    }

    public function testChangePasswordReturnsSuccessWhenAuthenticated(): void
    {
        $client = static::createClient();
        $user = $this->createUser();

        $client->loginUser($user);
        $client->request('GET', '/mot-de-passe');

        self::assertResponseIsSuccessful();
    }

    public function testWellKnownChangePasswordWhenAuthenticated(): void
    {
        $client = static::createClient();
        $user = $this->createUser();

        $client->loginUser($user);
        $client->request('GET', '/.well-known/change-password');

        self::assertResponseIsSuccessful();
    }

    public function testLoginPageContainsSsoButton(): void
    {
        $client = static::createClient();
        $crawler = $client->request('GET', '/connexion');

        self::assertResponseIsSuccessful();
        $ssoLink = $crawler->filter('a[href="/connection/sso/login"]');
        self::assertCount(1, $ssoLink);
    }

    public function testLogoutThrowsLogicException(): void
    {
        $this->expectException(\LogicException::class);

        $controller = new \App\Controller\SecurityController();
        $controller->logout();
    }

    private function createUser(): User
    {
        $em = static::getContainer()->get(EntityManagerInterface::class);

        $user = new User();
        $user->setEmail('test-security-'.uniqid().'@example.com');
        $user->setFirstName('Test');
        $user->setLastName('User');
        $user->setPassword('$2y$13$hashed');

        $em->persist($user);
        $em->flush();

        return $user;
    }
}
