<?php

namespace MintyPHP\Service\AddressBook;

use MintyPHP\Service\Directory\DirectoryServicesFactory;
use MintyPHP\Service\User\UserServicesFactory;

class AddressBookServicesFactory
{
    private ?AddressBookDirectoryGateway $addressBookDirectoryGateway = null;
    private ?AddressBookCustomFieldGateway $addressBookCustomFieldGateway = null;
    private ?AddressBookAvatarGateway $addressBookAvatarGateway = null;
    private ?AddressBookService $addressBookService = null;
    private ?UserServicesFactory $userServicesFactory = null;
    private ?DirectoryServicesFactory $directoryServicesFactory = null;

    public function createAddressBookService(): AddressBookService
    {
        if ($this->addressBookService !== null) {
            return $this->addressBookService;
        }

        $userFactory = $this->userServicesFactory();
        return $this->addressBookService = new AddressBookService(
            $userFactory->createUserAccountService(),
            $userFactory->createUserAssignmentService(),
            $this->createAddressBookDirectoryGateway(),
            $this->createAddressBookCustomFieldGateway(),
            $this->createAddressBookAvatarGateway()
        );
    }

    public function createAddressBookDirectoryGateway(): AddressBookDirectoryGateway
    {
        if ($this->addressBookDirectoryGateway !== null) {
            return $this->addressBookDirectoryGateway;
        }

        $directoryFactory = $this->directoryServicesFactory();
        return $this->addressBookDirectoryGateway = new AddressBookDirectoryGateway(
            $directoryFactory->createTenantService(),
            $directoryFactory->createDepartmentService(),
            $directoryFactory->createRoleService(),
            $directoryFactory->createDirectoryScopeGateway()
        );
    }

    public function createAddressBookCustomFieldGateway(): AddressBookCustomFieldGateway
    {
        return $this->addressBookCustomFieldGateway ??= new AddressBookCustomFieldGateway();
    }

    public function createAddressBookAvatarGateway(): AddressBookAvatarGateway
    {
        return $this->addressBookAvatarGateway ??= new AddressBookAvatarGateway(
            $this->userServicesFactory()->createUserAvatarService()
        );
    }

    private function userServicesFactory(): UserServicesFactory
    {
        return $this->userServicesFactory ??= new UserServicesFactory();
    }

    private function directoryServicesFactory(): DirectoryServicesFactory
    {
        return $this->directoryServicesFactory ??= new DirectoryServicesFactory();
    }
}
