<?php
namespace App\Http\Middleware;
use App\Support\ApiResponse;
use Closure;
use Illuminate\Http\Request;
final class EnsureApiScope {
 public function handle(Request $request, Closure $next, string $scope) {
  $key=$request->attributes->get('api_key_model');
  $scopes=$key?->scopes ?? [];
  if(!in_array('*',$scopes,true)&&!in_array($scope,$scopes,true)) return ApiResponse::error('INSUFFICIENT_SCOPE','The API key lacks the required permission.',403,['required_scope'=>$scope]);
  return $next($request);
 }
}
