<?php

namespace LQDN\Tests\Functional\Handler;

use LQDN\Command\UserUpdateByAdminCommand;
use LQDN\Command\UserUpdateTotalCommand;
use LQDN\Command\UserUpdateCumulCommand;
use LQDN\Command\UserCreateCommand;
use LQDN\Command\AdminUpdateTotalUsersCommand;
use LQDN\Tests\Functional\FunctionalTest;

class UserHandlerTest extends FunctionalTest
{
    public function testAdminUpdateTotalUsersCommand()
    {
        $this->container['command_handler']->handle(new AdminUpdateTotalUsersCommand());
        $this->assertSame(1000, (int) $this->getUser(1)['total']);
        $this->assertSame(872 , (int) $this->getUser(1)['cumul']);
        $this->assertSame(1000, (int) $this->getUser(2)['total']);
        $this->assertSame(686, (int) $this->getUser(2)['cumul']);
    }

    public function testUserUpdateFromAdmin()
    {
        $user = $this->getUser(1);
        $this->assertSame('Alice', $user['pseudo']);
        $this->assertSame('alice@example.org', $user['email']);
        $this->assertSame('RAS', $user['commentaire']);

        $this->container['command_handler']->handle(new UserUpdateByAdminCommand(1, 'Foobar', 'foobar@example.org', 'This is foobar avé dé accênts !', 2000, 1000));

        $user = $this->getUser(1);
        $this->assertSame('Foobar', $user['pseudo']);
        $this->assertSame('foobar@example.org', $user['email']);
        $this->assertSame('This is foobar avé dé accênts !', $user['commentaire']);
        $this->assertSame(2000, (int) $user['total']);
        $this->assertSame(1000, (int) $user['cumul']);
    }

    public function testUserCreateCommand()
    {
        $this->container['command_handler']->handle(new UserCreateCommand('eve@example.org', 'not a hash', 'Eve', 0, 0));
        $last_id = $this->container['db']->lastInsertId();
        $user = $this->getUser($last_id);

        $this->assertSame('eve@example.org', $user['email']);
    }

    public function testUserUpdateTotal()
    {
        $this->container['command_handler']->handle(new UserUpdateTotalCommand(1, 600));
        $user = $this->getUser(1);

        $this->assertSame(600, (int) $user['total']);
    }

    public function testUserUpdateCumul()
    {
        $this->container['command_handler']->handle(new UserUpdateCumulCommand(1, 600));
        $user = $this->getUser(1);

        $this->assertSame(600, (int) $user['cumul']);
    }

    /**
     * Retrieve a given user.
     *
     * @param int $id
     *
     * @return []
     */
    private function getUser($id)
    {
        return $this->container['db']->fetchAssoc("SELECT * FROM users WHERE id = $id");
    }
}