<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

class RoleMiddleware
{
    public function handle(Request $request, Closure $next, ...$roles)
    {
        $user = $request->user();

        if (!$user) {
            abort(403);
        }

        if (property_exists($user, 'is_active') && !$user->is_active) {
            abort(403, 'Account disabled.');
        }

        if (!in_array($user->role, $roles, true)) {
            abort(403, 'Unauthorized.');
        }

        if (
            in_array($user->role, ['lab_manager', 'lab_staff'], true)
            && !$user->lab_id
            && Route::is('frontdesk.*')
        ) {
            if ($request->expectsJson()) {
                abort(403, 'Account is not assigned to any lab.');
            }

            return redirect()
                ->route('dashboard')
                ->with('error', 'Your account is not assigned to a lab yet. Ask Super Admin to assign a lab before using frontdesk features.');
        }

        return $next($request);
    }
}
