<?php

namespace App\Http\Middleware;

use App\Domain\Shared\Models\Academy;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class SetCurrentAcademy
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($user = $request->user()) {
            // Load academy
            if ($user->academy_id) {
                $academy = Academy::find($user->academy_id);
                app()->instance('current_academy', $academy);
            }

            // Eager-load role with permissions for permission checks
            if ($user->role_id && !$user->relationLoaded('primaryRole')) {
                $user->load('primaryRole.permissions');
            } elseif (!$user->role_id && !$user->relationLoaded('roles')) {
                $user->load('roles.permissions');
            }
        }

        return $next($request);
    }
}
