<?php

namespace App\Http\Middleware;

use App\Core\Request;
use App\Core\Response;
use App\Domain\Services\TokenService;
use App\Exceptions\AuthException;

class Authenticate
{
    public function __construct(private TokenService $tokens)
    {
    }

    public function handle(Request $request, callable $next): Response
    {
        $token = $request->bearerToken();
        if (!$token) {
            throw new AuthException('Bearer token is required', 401);
        }

        $decoded = $this->tokens->validate($token);
        $request->setAttribute('token', $token);
        $request->setAttribute('jwt', $decoded);
        $request->setAttribute('user_id', (int)($decoded->user_id ?? $decoded->sub ?? 0));
        $request->setAttribute('role_id', (int)($decoded->role_id ?? 0));

        return $next($request);
    }
}
