<?php

declare(strict_types=1);

namespace App\Http\Middleware;

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

/**
 * Middleware: token.ip
 *
 * If the current request authenticated via a personal access token,
 * enforce the token's allowed_ips list. Session-authenticated requests
 * pass through untouched.
 */
class EnforceTokenIp
{
    public function handle($request, Closure $next): ResponseInterface
    {
        $token = BearerTokenResolver::current();

        if ($token !== null) {
            $ip = BearerTokenResolver::clientIp($request);
            if (! $token->ipAllowed($ip)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Request IP not allowed for this token.',
                    'code' => 'IP_NOT_ALLOWED',
                ], 403);
            }
        }

        return $next($request);
    }
}
