<?php

namespace AuthStack\UserDirectoryAPI\Service\test\units;

use mageekguy\atoum;
use AuthStack\UserDirectoryAPI\Model\Account as AccountModel;

class Account extends atoum\test
{
    public function testAccountOperations()
    {
        $this->given(

            // Create the account model and set url + bearer token
            $account = (new AccountModel())
                ->setBaseUrl($this->getBaseUrl())
                ->setBearerToken($this->getBearerToken())
        )
            ->and($username = 'dfrost')
            ->and($password = base64_encode(random_bytes(12)))

            ->then
                ->object($account)->isInstanceOf(AccountModel::class)

                // Create the account
                ->object(
                    /** @var $account AccountModel */
                    $account
                        ->setFirstName('Dyson')
                        ->setLastName('Frost')
                        ->setUsername($username)
                        ->setEmail('dyson.frost@hotmail.com')
                        ->setPassword($password)
                        ->save()
                )->isInstanceOf(AccountModel::class)

                // Authenticate the account - this errors out because account isn't active
                ->exception(function() use (&$account, $username, $password)
                {
                    $account->authenticate($username, $password);
                })->hasCode(460)

                // Activate the account
                ->boolean($account->activate())->isTrue()

                /** @var $account AccountModel */
                ->object($authenticated = $account->authenticate($username, $password))->isInstanceOf(AccountModel::class)

                // Update a property
                ->object($account->save(['first_name' => 'Changed']))->isInstanceOf(AccountModel::class)

                // Join an organization (we'll use the default one because it always exists)
                ->boolean($account->joinOrganization(1))->isTrue()

                ->boolean($account->leaveOrganization(1))->isTrue()

                // Delete the account
                ->boolean($account->delete())->isTrue()
        ;
    }

    protected function getBaseUrl(): string
    {
        return 'http://aud';
    }

    protected function getBearerToken(): string
    {
        return 'tLLT7bfjVcJ2XGMyzQocozn44H8nMKDd';
    }
}
