<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\services;

use apexl\Io\includes\Entity;
use apexl\Io\modules\user\enums\PermissionAction;
use apexl\Io\modules\user\interfaces\ChecksPermissions;
use apexl\Vault\interfaces\driver;

final readonly class EntityPermissionChecker
{
    public function __construct(private CurrentUserFactory $currentUserFactory) {}

    public function check(driver $query, Entity $entity, PermissionAction $action, ?string $tableAlias = null): void
    {
        if (!$entity instanceof ChecksPermissions) {
            return;
        }

        $user = $this->currentUserFactory->get();
        $result = $entity->checkPermission($action, $user, $tableAlias);

        if (!$result) {
            $query->whereRaw('false');

            return;
        }

        if (is_callable($result)) {
            ($result)($query, $user);
        }
    }
}