<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Auth\BearerTokenResolver;
use Closure;
use Hypervel\Support\Facades\Auth;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
 * Middleware: abilities:<ability>[,<ability>...]
 *
 * Passes when:
 * - request is session-authenticated (no token in play), OR
 * - the bearer token has ALL listed abilities (or wildcard '*').
 *
 * Note: this does not replace your RBAC role check; pair with a permission
 * check on the underlying user where appropriate.
 */
class CheckTokenAbilities
{
    public function handle($request, Closure $next, string ...$abilities): ResponseInterface
    {
        $user = Auth::user();
        if (! $user) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthenticated.',
                'code' => 'UNAUTHENTICATED',
            ], 401);
        }

        $token = BearerTokenResolver::current();

        // Session auth (no token) — abilities are not enforced at this layer.
        if ($token === null) {
            return $next($request);
        }

        foreach ($abilities as $ability) {
            if (! $token->can($ability)) {
                return response()->json([
                    'success' => false,
                    'message' => "Token missing ability: {$ability}",
                    'code' => 'MISSING_ABILITY',
                    'required' => $ability,
                ], 403);
            }
        }

        return $next($request);
    }
}
