<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Test;

use Chill\MainBundle\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * Prepare a client authenticated with a user.
 */
trait PrepareClientTrait
{
    /**
     * Create a new client with authentication information.
     *
     * @param string $username the username (default 'center a_social')
     * @param string $password the password (default 'password')
     *
     * @throws \LogicException
     */
    public function getClientAuthenticated(
        $username = 'center a_social',
        $password = 'password',
        $firewall = 'chill_main',
    ): KernelBrowser {
        if ('admin' === $username) {
            return $this->getClientAuthenticatedAsAdmin();
        }

        if (!$this instanceof WebTestCase) {
            throw new \LogicException(sprintf('The current class does not implements %s', WebTestCase::class));
        }

        $client = static::createClient();

        $userRepository = static::getContainer()->get(UserRepository::class);
        $user = $userRepository->findOneByUsernameOrEmail($username);

        if (null === $user) {
            throw new \RuntimeException(sprintf('user with username or email %s not found', $username));
        }

        $client->loginUser($user, $firewall);

        return $client;
    }

    public function getClientAuthenticatedAsAdmin(string $firewall = 'chill_main'): KernelBrowser
    {
        if (!$this instanceof WebTestCase) {
            throw new \LogicException(sprintf('The current class does not implements %s', WebTestCase::class));
        }

        $client = static::createClient();

        /** @var \Symfony\Component\Security\Core\User\InMemoryUserProvider $userProvider */
        $userProvider = static::getContainer()->get('security.user.provider.concrete.chill_in_memory');
        $user = $userProvider->loadUserByIdentifier('admin');
        $client->loginUser($user, $firewall);

        return $client;
    }
}
