<?php

namespace AuthStack\UserDirectory\Service\test\units;

use mageekguy\atoum;
use AuthStack\UserDirectory\Exceptions\OrganizationException;
use AuthStack\UserDirectory\Model\Organization as OrganizationModel;

class Organization extends atoum\test
{
    public function testOrganizationFlow()
    {
        /** @var $organization OrganizationModel */
        $this->given(
            $organization = (new OrganizationModel())
                            ->setBaseUrl($this->getBaseUrl())
                            ->setBasicAuthorization($this->getAuthToken())
                            ->setTitle('A test organization')
                            ->setDescription('This is test description')
                            ->setActive()
                            ->setAdditional(['address' => 'This is address'])

            )
            ->then
                // Create the organization
                ->object($organization = $organization->create())->isInstanceOf(OrganizationModel::class)

                // Create another organization with the same name
                ->exception(function() use (&$organization)
                {
                    $organization->create();

                })->isInstanceOf(OrganizationException::class)->hasCode(409)

                // Read organization
                ->object($org = $organization->read($organization->getID()))->isInstanceOf(OrganizationModel::class)

                // Update organization
                ->boolean($org->update(['title' => 'This is changed title']))->isTrue()
                ->string($org->getTitle())->isEqualTo('This is changed title')

                // Deactivate
                ->boolean($org->deactivate())->isTrue()

                // List members
                ->array($org->getMembers())->hasKeys(['data'])

                // List organizations
                ->array($org->listing())->hasKeys(['data'])

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

    protected function getBaseUrl($default = 'http://aud.app')
    {
        return function_exists('env') ? env('AUD_URL', $default) : $default;
    }

    protected function getAuthToken($default = 's2fNbDoMKF1hzd0OKrFiphUoLwH29Sgx')
    {
        return base64_encode(function_exists('env') ? env('AUD_TOKEN', $default) : $default);
    }
}