<?php

namespace Modules\Identity\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Modules\Identity\Enums\TokenAbility;
use Symfony\Component\HttpFoundation\Response;

class EnsureFastApiAgent
{
    /**
     * Identify the FastAPI AI agent by its token's ability scope rather than
     * a role — the agent has no admin-panel role, only a Sanctum token
     * restricted to exactly route:read, booking:create, booking:read.
     *
     * A customer token also carries those three abilities (plus more), so
     * membership alone can't tell agent and customer tokens apart — the
     * ability set must match exactly.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $token = $request->user()?->currentAccessToken();

        if (! $token) {
            abort(403, 'This action requires a FastAPI agent token.');
        }

        $actual = collect($token->abilities)->sort()->values()->all();
        $expected = collect(TokenAbility::fastApiAgentAbilities())->sort()->values()->all();

        if ($actual !== $expected) {
            abort(403, 'This action requires a FastAPI agent token.');
        }

        return $next($request);
    }
}
