<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureAccessLevel
{
    public function handle(Request $request, Closure $next, string ...$levels): Response
    {
        $user = $request->user();

        $tenantId = $request->attributes->get('tenant_id');
        $effectiveLevel = $tenantId ? $user?->tenantRole($tenantId) : $user?->access_level?->value;

        if (! $user || (! $user->isMasterAdmin() && ! in_array($effectiveLevel, $levels, true))) {
            return response()->json([
                'success' => false,
                'code' => 403,
                'message' => 'Anda tidak memiliki level akses yang diperlukan.',
            ], 403);
        }

        return $next($request);
    }
}
