<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\TestInfrastructure;

use apexl\Io\interfaces\GlobalDataInterface;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\enums\permissions\Common;
use apexl\Io\modules\user\exceptions\PermissionException;
use DI\DependencyException;
use DI\NotFoundException;
use function apexl\Io\container;

trait SpoofsGlobalUser
{
    protected bool $spoofGlobalUser = true;

    /**
     * @throws DependencyException
     * @throws NotFoundException
     * @throws PermissionException
     */
    protected function addSpoofedGlobalUser(): void
    {
        if (!$this->spoofGlobalUser) {
            return;
        }

        $globalData = container()->get(GlobalDataInterface::class);
        $entities = $globalData->getData('entities') ?? [];
        if (isset($entities['user'])) {
            return;
        }

        $user = userEntity::factory()->create($this->spoofedGlobalUserAttributes());
        $this->setSpoofedGlobalUserPermissions($user);
        container()->get(GlobalDataInterface::class)->addData(
            'entities',
            ['user' => ['entity' => $user, 'id' => $user->id]]
        );
    }

    protected function spoofedGlobalUserAttributes(): array
    {
        return [
            'first_name' => 'Spoofed',
            'last_name' => 'User',
            'email' => 'spoofeduser@example.com',
        ];
    }

    /**
     * @throws PermissionException
     */
    protected function setSpoofedGlobalUserPermissions(userEntity $user): void
    {
        $user->addPermission(Common::BYPASS);
    }
}
