<?php

namespace App\Domain\Identity\Services;

use App\Domain\Identity\Models\User;
use Illuminate\Contracts\Auth\Authenticatable;

/**
 * Bridges Laravel's Gate to the scoped permission engine (§66A).
 *
 * Any ability shaped like `module.action` is answered from
 * role_permission_scopes + user overrides, so a single source decides access
 * for gates, policies and the `permission` middleware alike.
 */
class AuthorizationGate
{
    public function __construct(private readonly PermissionScopeResolver $resolver) {}

    public function isPermissionKey(string $ability): bool
    {
        return (bool) preg_match('/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/', $ability);
    }

    /**
     * @return bool|null null means "not my call" — let policies decide.
     */
    public function check(Authenticatable $user, string $ability): ?bool
    {
        if (! $user instanceof User || ! $this->isPermissionKey($ability)) {
            return null;
        }

        if (! $user->isActive()) {
            return false;
        }

        return $this->resolver->scopeFor($user, $ability) !== null ? true : null;
    }
}
