<?php

namespace Ignite\Core\Entities\Filters;

use Ignite\Core\Contracts\Entities\Filters\QueryPermissionFilter;
use Illuminate\Support\Facades\App;

class QueryPermissionFilters
{
    /**
     * Get the scoped permission provider for the given permission.
     *
     * @param string $permission
     * @return QueryPermissionFilter|null
     */
    public static function for(string $permission): ?QueryPermissionFilter
    {
        $filterClassFQN = config('core.query_filters.permissions')[$permission] ?? null;
        if (! $filterClassFQN) {
            if (! App::runningUnitTests() && config('config.query_filters.debug')) {
                // Meant to be a helper while developing only. Added a debug config property on query_filters array
                // because this can be pretty noisy.
                logger()->debug("No permission filter has been registered for the given permission: $permission");
            }

            $filterClassFQN = NullQueryPermissionFilter::class;
        }

        $queryPermissionFilter = app($filterClassFQN);

        if (! $queryPermissionFilter instanceof QueryPermissionFilter) {
            throw new \UnexpectedValueException(
                "The class mapped to $permission needs to implement ".QueryPermissionFilter::class.
                ". It's mapped to: $filterClassFQN."
            );
        }

        return $queryPermissionFilter->forPermission($permission);
    }
}
