<?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()
    {
        $title = 'Test Organization ' . str_random(12);
        $updated_title = 'Updated Test Organization ' . str_random(12);

        /** @var $organization OrganizationModel */
        $this->given(
            $organization = (new OrganizationModel())
                            ->setBaseUrl($this->getBaseUrl())
                            ->setBasicAuthorization($this->getAuthToken())
                            ->setTitle($title)
                            ->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' => $updated_title]))->isTrue()
                ->string($org->getTitle())->isEqualTo($updated_title)

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

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

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

                // Hierarchy - list ID's of all organizations in this hierarchy (flat, 1d array)
                ->array($org->getHierarchyIDs())->isNotEmpty()
                ->array($org->getHierarchyIDs())->containsValues([$org->getID()])

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

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

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