<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\collections;

use apexl\Io\exceptions\RecordNotFoundException;
use apexl\Io\modules\user\entities\roleEntity;
use apexl\Io\modules\user\interfaces\PermissionInterface;
use Arrayy\Arrayy;
use Arrayy\Collection\AbstractCollection;

/**
 * @extends Arrayy<array-key, roleEntity>
 */
final class roleCollection extends AbstractCollection
{
    public static function createFromQueryResult(array $result): roleCollection
    {
        return self::createFromArray(
            array_filter(array_map(function ($result): ?roleEntity {
                    try {
                        return roleEntity::fromPrimaryKey($result->role);
                    } catch (RecordNotFoundException) {
                        return null;
                    }
                }, $result)
            )
        );
    }

    public function getType(): string
    {
        return roleEntity::class;
    }

    public function can(PermissionInterface|string $permission): bool
    {
        return $this->reduce(
            fn(bool $carry, roleEntity $role) => $carry || $role->can($permission),
            false
        )->first();
    }
}
