<?php

namespace Apexl\Io\User\Entities;

use Apexl\Io\Entity;
use Apexl\Io\Traits\HasCasts;
use Apexl\Io\User\Collections\PermissionCollection;
use Apexl\Io\User\Entities\Operators\RoleOperator;
use Apexl\Io\User\EntityFactories\RoleEntityFactory;
use Apexl\Io\User\Factories\RolePermissionManagerFactory;
use Apexl\Io\User\Interfaces\PermissionInterface;
use Apexl\Io\User\Services\RolePermissionManagerService;
use DateTimeImmutable;

/**
 * @property int $id
 * @property string $name
 * @property DateTimeImmutable $created
 * @property UserEntity $created_by
 * @property DateTimeImmutable $modified
 * @property UserEntity $modified_by
 * @property RoleOperator $operator
 * @method \Apexl\Io\User\Entities\RoleEntity[] loadMultiple(array $conditions = [], array $orderBy = [], bool|int $limit = false, bool|int $offset = false)
 *
 * @method static \Apexl\Io\User\EntityFactories\RoleEntityFactory factory()
 */
class RoleEntity extends Entity
{
    public const string TABLE = 'roles';

    protected const string OPERATOR = RoleOperator::class;

    use HasCasts;

    private RolePermissionManagerService $permissionManager;

    public function __construct()
    {
        parent::__construct();
        $this->permissionManager = \Apexl\Io\container()->make(RolePermissionManagerFactory::class)->make($this);

    }

    public function loadByName(string $name): array
    {
        return $this->applyOperatorResponse($this->operator()->loadByName($name));
    }

    public static function entityFactoryClass(): string
    {
        return RoleEntityFactory::class;
    }

    public function getEntityType(): string
    {
        return __CLASS__;
    }

    public function addPermission(PermissionInterface $permission): void
    {
        if (!$this->can($permission)) {
            $this->permissionManager->add($permission);
        }
    }

    public function can(PermissionInterface|string $permission): bool
    {
        return $this->permissionManager->can($permission);
    }

    public function permissions(): PermissionCollection
    {
        return $this->permissionManager->permissions();
    }

    public function removePermission(PermissionInterface $permission): void
    {
        if ($this->can($permission)) {
            $this->permissionManager->remove($permission);
        }
    }
}
