<?php

namespace App\Http\Middleware;

use Closure;

class RoleMiddleware
{
    public function handle($request, Closure $next, $role = null)
    {
        $user = $request->user();

        if (!$role || !$user) {
            return $next($request);
        }

        $allowed = array_map('trim', explode(',', $role));
        $has = false;

        // Ưu tiên session cached role để tránh query
        if ($request->hasSession()) {
            $sessionRole = $request->session()->get('role');
            $has = $sessionRole && in_array($sessionRole, $allowed, true);
        }

        // Kiểm tra qua model method nếu chưa có kết quả
        if (!$has && method_exists($user, 'hasRole')) {
            foreach ($allowed as $r) {
                if ($user->hasRole($r)) {
                    $has = true;
                    break;
                }
            }
        }

        if (!$has) {
            return response()->json(['message' => 'Forbidden'], 403);
        }

        return $next($request);
    }
}
