<?php

namespace App\Modules\Integrations\Platform\Middleware;

use App\Modules\Integrations\Platform\Models\ApiToken;
use App\Modules\Integrations\Platform\Support\ApiErrorResponse;
use App\Modules\Integrations\Platform\Support\ApiResponseFactory;
use Closure;
use Illuminate\Http\Request;

final class EnsureTokenScopes
{
    public function __construct(private readonly ApiResponseFactory $responses) {}

    public function handle(Request $request, Closure $next, string $scopesCsv = '')
    {
        /** @var ApiToken|null $token */
        $token = $request->attributes->get('api_token');
        if (! $token instanceof ApiToken) {
            return $this->responses->error(
                new ApiErrorResponse('auth.missing_token', 'Missing API token.'),
                401,
            );
        }

        $required = array_values(array_filter(array_map('trim', explode(',', $scopesCsv))));
        if ($required === []) {
            return $next($request);
        }

        $granted = array_fill_keys((array) ($token->scopes ?? []), true);
        foreach ($required as $scope) {
            if (! isset($granted[$scope])) {
                return $this->responses->error(
                    new ApiErrorResponse('auth.insufficient_scope', 'API token lacks required scope.', [
                        'required' => $required,
                    ]),
                    403,
                );
            }
        }

        return $next($request);
    }
}

